<?php

namespace App\Models;

use App\Enums\SmsTempEnum;
use App\Jobs\ProcessPodcast;
use App\Jobs\SendChangeOrderMessage;
use App\Jobs\SendSmsMessageJob;
use App\Services\AlipayMessageService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\AntchainService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\TemplateProcessor;

/**
 *
 * @property  integer mini_id
 * @property  integer biz_type
 * @property  string trade_no
 */
class Order extends Model
{
    use HasFactory;

    protected $table = 'sp_order_2';
    protected $primaryKey = 'id';
    public $timestamps = false;

    const RISK_SKIP_NOT = 0;//不跳过风控
    const RISK_SKIP_YES = 1;//跳过风控

    const FINANCING_TYPE_RONG = 1;//融资
    const FINANCING_TYPE_NORONG = 2;//非融资

    //sync_status报单同步状态：1待同步 2同步成功 3同步失败
    const ORDER_NOT_SYNC = 1;//1待同步
    const ORDER_SYNC_SUCCESS = 2;//同步成功
    const ORDER_SYNC_FAIL = 3;//同步失败

    const ORDER_FINANCING_TYPE_NAME_LIST = [
        1 => '融资',
        2 => '非融资'
    ];

    const FINANCING_TYPE_LIST = [
        1 => '是',
        2 => '否'
    ];
    //订单类型
    const ORDER_PAY_TYPE_ANTCHAIN = 1;//智能合同代扣
    const ORDER_PAY_TYPE_ZM = 2;//芝麻信用
    const ORDER_PAY_TYPE_HUABEI = 3;//花呗

    const ORDER_PAY_TYPE = [
        "1" => '智能合同',
        "2" => '芝麻信用',
        "3" => '花呗',
    ];

    //订单合同类型
    const ORDER_CONTRACT_TYPE_ANTCHAIN = 1;//智能合同代扣
    const ORDER_CONTRACT_TYPE_ESIGN = 2;//E签宝

    //是否选择联通套餐
    const UNICOM_CHOOSE_YES = 1;//是
    const UNICOM_CHOOSE_NO = 2;//否

    //是否是异常流程
    const ORDER_IS_ABNORMAL = 1;//是
    const ORDER_NOT_ABNORMAL = 2;//否

    //是否是续租订单
    const ORDER_IS_RENEWAL = 1;//是
    const ORDER_NOT_RENEWAL = 2;//否

    //花呗结算状态
    const ORDER_HUABEI_SETTLE_STATUS_NO = 1;//未结算
    const ORDER_HUABEI_SETTLE_STATUS_YES = 2;//已结算
    const ORDER_HUABEI_SETTLE_STATUS_REFUSE = 3;//拒绝结算

    const ORDER_HUABEI_SETTLE_STATUS_LIST = [
        '1' => '未结算',
        '2' => '已结算',
        '3' => '拒绝结算',
    ];


    public function order_goods()
    {
        return $this->hasOne(OrderGoods::class, 'order_id', 'id');
    }

    public function shop()
    {
        return $this->hasOne(ShopUser::class, 'member_id', 'seller_id');
    }

    public function authentic_log()
    {
        return $this->hasOne(AuthenticLog::class, 'order_id', 'id');
    }


    /**
     * @param int $id
     * @return Order|Order[]|\LaravelIdea\Helper\App\Models\_IH_Order_C|null
     */
    public static function findById(int $id)
    {
        return self::find($id);
    }

    /**
     * @param string $tradeNo
     * @return Order|null
     */
    public static function findByTradeNo(string $tradeNo)
    {
        return self::where(['trade_no' => $tradeNo])->first();
    }

    //创建订单信息
    protected function createOrder($miniId, $request, $user)
    {
        $amount = $request['amount'];
        $realname = $request['realname'];
        $mobile = $request['mobile'];
        $address = $request['address'];
        $goods_id = $request['goods_id'];
        $setmeal_id = $request['setmeal_id'];
        $spec_id = $request['spec_id'];
        $is_renewal = isset($request['is_renewal']) ? $request['is_renewal'] : self::ORDER_NOT_RENEWAL;
        $parent_order_id = isset($request['parent_order_id']) ? $request['parent_order_id'] : '';
        $relation_id = isset($request['relationId']) ? $request['relationId'] : '';
        $pact_type = isset($request['pact_type']) ? $request['pact_type'] : '2';
        $emergency_contact = isset($request['emergency_contact']) ? $request['emergency_contact'] : '';
        $huabei_stages = isset($request['huabei_stages']) ? $request['huabei_stages'] : 0;
        $contact_name = isset($request['contact_name']) ? $request['contact_name'] : '';
        $contact_mobile = isset($request['contact_mobile']) ? $request['contact_mobile'] : '';
        $insurance = isset($request['insurance']) ? $request['insurance'] : '7';
        //推广参数
        $sale_user_id = isset($request['sale_user_id']) ? $request['sale_user_id'] : '';

        $deposit = isset($request['deposit']) ? $request['deposit'] : '';

        if (empty($amount)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请选择商品数量', 'data' => []];
        }
        if (empty($realname) || empty($mobile) || empty($address)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '收货人手机号或姓名地址不能为空', 'data' => []];
        }
        if (empty($goods_id) || empty($setmeal_id) || empty($spec_id)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '缺少商品参数', 'data' => []];
        }
        //非续租减库存
        if ($is_renewal == Order::ORDER_NOT_RENEWAL) {
            GoodsSetmeal::where([['goods_id', $goods_id], ['id', $setmeal_id]])->decrement('quantity', $amount);
        }

        $config = Config::settingDetail();
        $age = getAgeByID($user['cert_no']);
        if ($user['cert_no']) {
            if ($age < $config['min_age'] || $age > $config['max_age']) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '您年龄不符合要求', 'data' => []];//，需要大于18岁小于40岁
            }
        }
        if ($config['channel_time']) {
            $channel_time = bcsub(time(), $config['channel_time'] * 86400);
            $channel_time_sale_user_id = $this->where('uid', $user['id'])->where('create_time', '>', $channel_time)->orderBy('id', 'desc')->value('sale_user_id');
            if ($channel_time_sale_user_id) {
                $sale_user_id = $channel_time_sale_user_id;
            }
        }

        //商品
        $goods = Goods::checkGoodsStatus($goods_id);
        if (empty($goods)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '商品不存在', 'data' => []];
        }
        if (ShopUser::where('member_id', $goods['member_id'])->value('emergency_contact') == ShopUser::SHOP_USER_EMERGENCY_CONTACT_OPEN) { // 紧急联系人必填
            if (empty($contact_name) || empty($contact_mobile)) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '该订单必须填写紧急联系人信息，如页面无输入框，请下拉刷新页面！', 'data' => []];
            }
            if (trim($realname) == trim($contact_name) || trim($mobile) == trim($contact_mobile)) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人信息不能与收货人信息一致', 'data' => []];
            }
        }
        //套餐
        $setmeal = GoodsSetmeal::CheckGoodsSetmeal($goods_id, $setmeal_id);
        if (empty($setmeal)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '套餐不存在', 'data' => []];
        }
        //租期
        $spec = GoodsSpec::CheckGoodsSpec($goods_id, $setmeal_id, $spec_id);
        if (empty($spec)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '租期信息不存在', 'data' => []];
        }

        if (!empty($request['PackageID']) && !empty($request['AccessuserID'])) {
            $order = $this->where([['other_order_id', $request['PackageID']], ['other_user_id', $request['AccessuserID']]])
                ->select('id as order_id', 'trade_no')->first();
            $order = $order ? $order->toArray() : [];
            if (!empty($order)) {
                $order_data['realname'] = $realname;
                $order_data['mobile'] = $mobile;
                $order_data['address'] = preg_replace('/\s*/', '', stripslashes(strval($request['address'])));
                $order_data['prov'] = $request['prov'];
                $order_data['city'] = $request['city'];
                $order_data['area'] = $request['area'];
                $this->where([['other_order_id', $request['PackageID']], ['other_user_id', $request['AccessuserID']]])->update($order_data);
                return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '订单创建成功', 'data' => $order];
            }
        } else {
            $time = strtotime(date('Y-m-d'));
            $order = $this->from('sp_order_2 as o')->leftjoin('sp_order_goods_2 as g', 'o.id', 'g.order_id')->where([['g.goods_id', $goods_id], ['g.setmeal_id', $setmeal_id], ['g.spec_id', $spec_id], ['o.status', OrderService::ORDER_STATUS_SIGN_NOCHECK], ['o.amount', $amount], ['o.create_time', '>', $time], ['o.uid', $user['id']]])->select('o.id as order_id', 'o.trade_no')->first();
            $order = $order ? $order->toArray() : [];
            if (!empty($order)) {
                return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '订单创建成功', 'data' => $order];
            }
        }

        $order_data = [];
        $order_sn = createNo();
        if (!$sale_user_id) {
            $order_data['seller_id'] = $goods['member_id'];
            // $order_data['seller_id'] = '1731928096';
        }
        $insurance_money = '0.00';
        if ($insurance) {
            $order_data['is_insurance_choose'] = $insurance;
            $insurance_money = GoodsService::getGoodsInsurance($insurance);
        }
        if ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH) {//按月
            if ($pact_type == GoodsService::GOODS_PACT_TYPE_FIXED) {
                $spec['lease_price'] = bcdiv($spec['lease_time'] * $spec['lease_price'] * $amount - $setmeal['buyout_price'] * $amount, $spec['lease_time'], 6);
            }
            $order_data['rent_total'] = sprintf("%.2f", $spec['lease_time'] * $spec['lease_price'] * $amount + $insurance_money);//总租金
            $order_data['month_total'] = $spec['lease_time'];
            $month_total = $spec['lease_time'];
        } elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY) {//按天
            if ($pact_type == GoodsService::GOODS_PACT_TYPE_FIXED) {
                $spec['day_price'] = bcdiv($spec['lease_time'] * $spec['day_price'] * $amount - $setmeal['buyout_price'] * $amount, $spec['lease_time'], 6);
            }
            $order_data['rent_total'] = sprintf("%.2f", $spec['lease_time'] * $spec['day_price'] * $amount + $insurance_money);//总租金
            $order_data['month_total'] = floor($spec['lease_time'] / 30);
            $month_total = floor($spec['lease_time'] / 30);

            $spec['lease_price'] = bcdiv($order_data['rent_total'], $month_total, 2);


        } elseif ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM) {//自定义租期
            $cuntom = GoodsCustomRent::where([['goods_id', $goods_id], ['setmeal_id', $setmeal_id], ['spec_id', $spec_id], ['is_delete', GoodsService::GOODS_NO_DELETE_STATUS]])->select('lease_price')->get();
            $cuntom = $cuntom ? $cuntom->toArray() : [];
            $order_data['rent_total'] = sprintf("%.2f", array_sum(array_column($cuntom, 'lease_price')) * $amount + $insurance_money);
            $order_data['month_total'] = count($cuntom);
            $month_total = count($cuntom);
        }
        // 订单所属平台
        $order_data['mini_id'] = $miniId;

        $order_data['uid'] = $user['id'];
        $order_data['trade_no'] = $order_sn;
        $order_data['remark'] = !empty($request['remark']) ? $request['remark'] : '';
        $order_data['user_email'] = !empty($request['email']) ? $request['email'] : '';
        $order_data['realname'] = $realname;
        $order_data['mobile'] = $mobile;
        $order_data['address'] = preg_replace('/\s*/', '', stripslashes(strval($address)));
        $order_data['prov'] = !empty($request['prov']) ? $request['prov'] : '';
        $order_data['city'] = !empty($request['city']) ? $request['city'] : '';
        $order_data['area'] = !empty($request['area']) ? $request['area'] : '';
        $order_data['create_time'] = time();
        $order_data['update_time'] = time();
        $order_data['amount'] = intval($amount);
        $order_data['pay_type'] = $goods['pay_type'];
        $order_data['payer_user_id'] = $user['user_id'];

//定位位置 手机品牌

        $location = isset($request['location']) ? $request['location'] : '';
        $location = isset($location['province']) ? $location['province'] . $location['city'] . $location['district'] . $location['streetNumber']['street'] . $location['streetNumber']['number'] : $location;
        $order_data['location'] = $location;
        $order_data['phone_brand'] = isset($request['phone_brand']) ? $request['phone_brand'] : '';

        if (!empty($request['PackageID']) && !empty($request['AccessuserID'])) {
            $order_data['other_order_id'] = $request['PackageID'];
            $order_data['other_user_id'] = $request['AccessuserID'];
        }
        //花呗分期数据
        if (!empty($huabei_stages)) {
            $order_data['pay_type'] = OrderLease::LEASE_PAY_TYPE_HUABEI;
            $order_data['huabei_stages'] = $huabei_stages;
            $order_data['huabei_fee_bear'] = GoodsHuabei::getHuabeiFeeBear($goods_id, $setmeal_id, $spec_id, $huabei_stages);
        }
        if (!empty($contact_name) && !empty($contact_mobile)) {
            $order_data['emergency_contact'] = $contact_name . $contact_mobile;
        }
        $order_from = !empty($request['order_from']) ? $request['order_from'] : 'search';
        $order_data['order_from'] = $order_from;

        if (intval($order_from) > 0) {
            $where_sale1 = [];
            $where_sale1[] = ['sale_user_id', $order_from];
            $sale = SaleUser::GetSaleUser($where_sale1);

            $order_data['sale_user_id'] = $order_from;
            $order_data['shopcity'] = $sale['shopcity'];
            $order_data['reward'] = $sale['rate_money'];
            $order_data['order_from'] = $sale['type'] == SaleUser::SALE_ONLINE ? 'saleOnline' : 'saleOffline';
        }

        $order_data['relation_id'] = $relation_id;
        $order_data['contract_type'] = $goods['contract_type'];
        $order_data['sign_num'] = $goods['sign_num'];
        $order_data['is_insurance'] = $goods['is_insurance'];
        $shopuser = ShopUser::where('member_id', $goods['member_id'])->select('account', 'account_type')->first();
        $shopuser = obToArray($shopuser);
        $shopRecharge = ShopRecharge::where('member_id', $goods['member_id'])->select('risk_credit_status', 'risk_credit_amount')->first();
        $shopRecharge = obToArray($shopRecharge);
        $order_data['is_skip'] = self::RISK_SKIP_YES;
        if (!empty($shopRecharge)) {
            $order_data['is_skip'] = $shopRecharge['risk_credit_status'] == ShopRecharge::SERVICE_STATUS_OPEN ? self::RISK_SKIP_NOT : self::RISK_SKIP_YES;
        }
        if (!empty($shopuser)) {
            $order_data['financing_type'] = $shopuser['account'];
        }
        $begin_time = date("Y-m-d H:i:s", time() + $setmeal['start_date'] * 24 * 3600);//租期开始时间
        //续租订单查询原订单号关联
        if ($is_renewal == self::ORDER_IS_RENEWAL && !empty($parent_order_id)) {
            $parent_order = Order::where([['uid', $user['id']], ['id', $parent_order_id], ['status', OrderService::ORDER_STATUS_TOBE_RETURNED]])->select('trade_no', 'end_time', 'order_from', 'seller_id')->first();
            $parent_order = obToArray($parent_order);
            if (!empty($parent_order)) {
                $order_data['is_renewal'] = self::ORDER_IS_RENEWAL;
                $order_data['parent_order_no'] = $parent_order['trade_no'];
                $order_data['order_from'] = $parent_order['order_from'];
                $order_data['seller_id'] = $parent_order['seller_id'];
                $begin_time = $parent_order['end_time'];//租期开始时间接原订单结束时间
            }
        }
        $lease_time = $spec['lease_time'];
        if ($setmeal['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH) {//租期按月
            $end_time = date("Y-m-d H:i:s", strtotime("+$lease_time months", strtotime($begin_time)));
        } else {//租期按天/自定义租期
            $end_time = date("Y-m-d H:i:s", strtotime("+$month_total months", strtotime($begin_time)));
        }
        $order_data['begin_time'] = $begin_time;
        $order_data['end_time'] = $end_time;
        $order_data['form_id'] = isset($request['form_id']) ? $request['form_id'] : '';//模板消息form_id
        //联通套餐
        $unicom = isset($request['unicom']) ? $request['unicom'] : '';
        //选择联通套餐
        if ($unicom) {
            $order_data['is_unicom_choose'] = Order::UNICOM_CHOOSE_YES;
        }

        if (!empty($sale_user_id) && $sale_user_id > 0) {

            $where_sale = [];
            $where_sale[] = ['sale_user_id', $sale_user_id];
            $sale = SaleUser::GetSaleUser($where_sale);

            $member_id = ShopUser::where('id', $sale['shop_user_id'])->value('member_id');
            $order_data['seller_id'] = $member_id;
            $order_data['sale_user_id'] = $sale_user_id;
            $order_data['shopcity'] = $sale['shopcity'];
            $order_data['reward'] = $sale['rate_money'];
            $order_data['order_from'] = $sale['type'] == SaleUser::SALE_ONLINE ? 'saleOnline' : 'saleOffline';
        }

        if (empty($order_data['seller_id'])) {
            $order_data['seller_id'] = '1731928096';
        }
        $order_data['status'] = isset($request['status']) ? $request['status'] : OrderService::ORDER_STATUS_SIGN_NOCHECK; //待认证

        $order_data['emergency_contact'] = $emergency_contact;

        $order_data['foregift'] = $setmeal['foregift'];

        DB::beginTransaction();
        $order_id = $this->insertGetId($order_data);

        if ($order_id) {

            //费率查询记录
            $month_num = getMonthNum($begin_time, $end_time);
            OrderRate::addOrderRate($order_id, $goods_id, $order_from, $goods['member_id'], self::RISK_SKIP_YES, $month_num, $shopuser['account'], '', '', $goods['pay_type']);
            $order = array(
                'id' => $order_id,
                'lease_set' => $setmeal['lease_set'],
                'lease_time' => $spec['lease_time'],
                'begin_time' => $begin_time,
                'lease_price' => $spec['lease_price'],
                'amount' => intval($amount),
                'pay_type' => $goods['pay_type'],
                'month_total' => $month_total,
                'goods_id' => $goods_id,
                'setmeal_id' => intval($setmeal_id),
                'spec_id' => $spec_id,
                'is_insurance_choose' => $insurance,
                'is_rent_choose' => '7'
            );
            //生成账单
            $res_data = OrderLease::createOrderLease($order, GoodsService::GOODS_SETMEAL_NO_HUABEI, '');
            if ($res_data['status'] == 200) {
                $order_lease_data = $res_data['data'];
            }


            //短信通知

            $order_goods_data = [];
            $order_goods_data['order_id'] = $order_id;
            $order_goods_data['goods_id'] = intval($goods_id);
            $order_goods_data['goods_title'] = $goods['title'];
            $order_goods_data['pact_type'] = $pact_type;
            $order_goods_data['imgurl'] = $goods['imgurl'];
            $order_goods_data['convey_type1'] = $goods['convey_type1'];
            $order_goods_data['convey_type2'] = $goods['convey_type2'];
            $order_goods_data['setmeal_id'] = intval($setmeal_id);
            $order_goods_data['setmeal_title'] = $setmeal['title'];
            $order_goods_data['lease_set'] = $setmeal['lease_set'];
            $order_goods_data['spec_id'] = $spec_id;
            $order_goods_data['lease_time'] = $spec['lease_time'];
            $order_goods_data['lease_price'] = $spec['lease_price'];
            $order_goods_data['setmeal_price'] = $setmeal['buyout_price'];
            $order_goods_data['website_price'] = $setmeal['price'];
            if ($is_renewal == self::ORDER_IS_RENEWAL) {
                $order_goods_data['start_date'] = $setmeal['start_date'];
            } else {
                $order_goods_data['start_date'] = 0;
            }
            if ($pact_type == GoodsService::GOODS_PACT_TYPE_GIVE) {
                $order_goods_data['setmeal_foregift'] = $order_data['rent_total'] + $insurance_money;
                $order_goods_data['setmeal_price'] = 0;
//                $order_goods_data['setmeal_foregift'] = $setmeal['foregift'];//修改的地方后期需要改动
            } else {
//                $order_goods_data['setmeal_price'] = bcsub($setmeal['price']+$insurance_money,$order_data['rent_total'],2);
                $order_goods_data['setmeal_price'] = $setmeal['buyout_price'] > 0 ? $setmeal['buyout_price'] : 0;
                $order_goods_data['setmeal_foregift'] = $order_data['rent_total'] + $order_goods_data['setmeal_price'] + $insurance_money;

            }
            $order_goods_data['is_buy_out'] = $setmeal['is_buy_out'];
            $order_goods_data['create_time'] = time();
            $res = OrderGoods::insert($order_goods_data);


            if ($res) {
                DB::commit();
                $data['order_id'] = $order_id;
                AlipayMessageService::sendChangeOrderMessage($order_id);

                ProcessPodcast::dispatch($order_id);

                return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '订单创建成功', 'data' => $data];
            } else {
                DB::rollBack();
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单创建失败', 'data' => []];
            }
        } else {
            DB::rollBack();
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单创建失败', 'data' => []];
        }
    }

    //小程序个人中心获取订单数量
    protected function alipayOrderCount($miniId, $user_id)
    {
        $data['no_pay'] = $this->where([['uid', $user_id], ['mini_id', $miniId]])->wherein('status', [OrderService::ORDER_STATUS_NOT_PAY, OrderService::ORDER_STATUS_SIGN_NOTPAY])->count();
        $data['no_delivery'] = $this->where([['uid', $user_id], ['mini_id', $miniId], ['status', OrderService::ORDER_STATUS_PAY_SUCCESS]])->count();
        $data['no_send'] = $this->where([['uid', $user_id], ['mini_id', $miniId], ['status', OrderService::ORDER_STATUS_DELIVER_SUCCESS]])->count();
        $data['renting'] = $this->where([['uid', $user_id], ['mini_id', $miniId]])->wherein('status', [OrderService::ORDER_STATUS_CONFIRM_GOODS, OrderService::ORDER_STATUS_OVERDUE])->count();
        return $data;
    }


    //小程序订单列表
    protected function alipayOrderList($miniId, $request, $user_id)
    {
        $page = !empty($request['page']) ? $request['page'] : 1;
        $pageSize = !empty($request['pageSize']) ? $request['pageSize'] : 5;
        $where[] = ['o.uid', $user_id]; // 所属用户
//        $where[] = ['o.mini_id', $miniId]; // 所属平台
        $wherein = [];
        if (!empty($request['order_status'])) {
            if ($request['order_status'] == OrderService::ORDER_STATUS_NOT_PAY) { //待付款
                $wherein = [OrderService::ORDER_STATUS_NOT_PAY, OrderService::ORDER_STATUS_SIGN_NOTPAY];
            } elseif ($request['order_status'] == OrderService::ORDER_STATUS_PAY_SUCCESS) { //待发货
                $wherein = [OrderService::ORDER_STATUS_PAY_SUCCESS, OrderService::ORDER_STATUS_SIGN_NOTRISK];
            } elseif ($request['order_status'] == OrderService::ORDER_STATUS_TOBE_RETURNED) { //退货订单
                $wherein = [OrderService::ORDER_STATUS_TOBE_RETURNED, OrderService::ORDER_STATUS_RETURN_APPLICATION, OrderService::ORDER_STATUS_RETURN_APP_AGREE, OrderService::ORDER_STATUS_RETURN_APP_REFUSE, OrderService::ORDER_STATUS_RETURN_DELIVER_SUCCESS, OrderService::ORDER_STATUS_RETURN_CONFIRM_GOODS, OrderService::ORDER_STATUS_RETURN_OVERDUE];
            } elseif ($request['order_status'] == OrderService::ORDER_STATUS_COMPLETED) { //交易完成
                $wherein = [OrderService::ORDER_STATUS_COMPLETED, OrderService::ORDER_STATUS_RENEWAL_APP_PAY_SUCCESS, OrderService::ORDER_STATUS_BUYOUT_PAY, OrderService::ORDER_STATUS_ADVANCE_RETURN_FINISH, OrderService::ORDER_STATUS_REFUND_FINISH, OrderService::ORDER_STATUS_RETURN_FINISH];
            } elseif ($request['order_status'] == OrderService::ORDER_STATUS_RENEWAL_APPLICATION) { //续租订单
                $wherein = [OrderService::ORDER_STATUS_RENEWAL_APPLICATION, OrderService::ORDER_STATUS_RENEWAL_APP_AGREE, OrderService::ORDER_STATUS_RENEWAL_APP_REFUSE];
            } elseif ($request['order_status'] == OrderService::ORDER_STATUS_CONFIRM_GOODS) { //租用中
                $wherein = [OrderService::ORDER_STATUS_CONFIRM_GOODS, OrderService::ORDER_STATUS_OVERDUE, OrderService::ORDER_STATUS_REPAYMENT];
            } else {
                $where[] = ['o.status', $request['order_status']];
            }
        }
        if (!empty($wherein)) {
            $order = $this->from('sp_order_2 as o')->where($where)->wherein('o.status', $wherein)
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->select('o.id', 'o.mini_id', 'o.biz_type', 'o.is_insurance_choose', 'o.is_insurance_choose_custom',
                    'm.certify_id as face_flow_id', 'o.rent_total', 'o.month_total',
                    'o.amount', 'o.status', 'o.rights_auth_no', 'o.pay_type', 'o.sign_status',
                    'o.create_time', 'o.begin_time', 'o.end_time', 'o.flow_id',  'o.guarantee_status',
                    'og.goods_id', 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.pact_type', 'o.withhold_status',
                    'su.shopname', 'su.member_id', 'su.is_show', 'm.esign_user_id', 'o.order_from', 'o.contract_type')
                ->orderBy('o.id', 'desc')
                ->paginate($pageSize);
        } else {
            $order = $this->from('sp_order_2 as o')->where($where)
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->select('o.id', 'o.mini_id', 'o.biz_type', 'o.is_insurance_choose', 'o.is_insurance_choose_custom', 'm.certify_id as face_flow_id', 'o.rent_total', 'o.month_total', 'o.amount', 'o.status', 'o.rights_auth_no', 'o.pay_type', 'o.sign_status',
                    'o.create_time', 'o.begin_time', 'o.end_time', 'o.flow_id',  'o.guarantee_status',
                    'og.goods_id', 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.pact_type', 'o.withhold_status',
                    'su.shopname', 'su.member_id', 'su.is_show', 'm.esign_user_id', 'o.order_from', 'o.contract_type')
                ->orderBy('o.id', 'desc')
                ->paginate($pageSize);
        }
        $order = $order ? $order->toArray() : [];
        if (!empty($order['data'])) {
            foreach ($order['data'] as $k => $v) {
                $order['data'][$k]['order_status_name'] = OrderService::ORDER_STATUS_NAME_LIST[$v['status']];
                $order['data'][$k]['lease_time'] = date("Y.m.d", strtotime($v['begin_time'])) . '-' . date("Y.m.d", strtotime($v['end_time']));
                $order['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                unset($order['data'][$k]['begin_time']);
                unset($order['data'][$k]['end_time']);
                $res = AuthenticLog::where(['order_id' => $v['id'], 'status' => AuthenticLog::AUTHENTIC_STATUS_PASS])->first();
                if ($v['status'] == OrderService::ORDER_STATUS_NOT_PAY) {
                    $order['data'][$k]['is_authentic'] = obToArray($res) ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE;
                }
                if (!obToArray($res)) {
                    $order['data'][$k]['face_flow_id'] = 0;
                }
                $order['data'][$k]['is_edit'] = 0;
            }
        }
        return $order;
    }

    //小程序订单详情
    protected function alipayOrderInfo($order_id, $user_id)
    {
        $where[] = ['o.uid', $user_id];
        $where[] = ['o.id', $order_id];
        $order = $this->from('sp_order_2 as o')->where($where)
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', 'o.seller_id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select('o.id as order_id', 'o.mini_id', 'o.biz_type', 'o.is_insurance_choose', 'o.is_insurance_choose_custom', 'o.face_flow_id',
                'o.seller_id as member_id', 'o.status', 'o.realname', 'o.mobile',
                'o.prov', 'o.city', 'o.area', 'o.address', 'o.amount',
                'o.begin_time', 'o.end_time', 'o.rent_total', 'o.month_total',
                'o.month_paid', 'o.foregift_deduct', 'o.rights_auth_no', 'o.remark',
                'o.pay_type', 'o.trade_no', 'o.create_time', 'o.sign_status', 'o.pact_url', 'o.flow_id',   'og.setmeal_foregift', 'og.goods_title', 'og.lease_set', 'og.lease_time as order_lease_time', 'og.lease_price', 'og.imgurl', 'og.setmeal_title', 'og.setmeal_price', 'og.convey_type1', 'og.convey_type2', 'og.is_buy_out', 'su.shopname', 'su.is_show', 'm.esign_user_id', 'og.goods_id', 'og.setmeal_id', 'og.spec_id', 'o.order_from', 'o.contract_type', 'og.pact_type', 'o.is_renewal', 'o.parent_order_no')
            ->first();
        $order = $order ? $order->toArray() : [];
        if (!empty($order)) {
            $order['convey_type'] = (!empty($order['convey_type1']) && !empty($order['convey_type2'])) ? '寄出' . GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$order['convey_type1']] . '/退货' . GoodsService::GOODS_RETURN_CONVEY_TYPE_NAME_LIST[$order['convey_type2']] : '';
            $order['lease_time'] = date("Y.m.d", strtotime($order['begin_time'])) . '-' . date("Y.m.d", strtotime($order['end_time']));
            $order['is_buy_out'] = !empty($order['is_buy_out']) ? GoodsService::GOODS_BUYOUT_NAME_LIST[$order['is_buy_out']] : '';
            $order['pact_type_name'] = GoodsService::getGoodsPactName($order['pact_type']);
            $order['status_name'] = OrderService::ORDER_STATUS_NAME_LIST[$order['status']];
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['buyout_amount'] = 0;
            if ($order['status'] == OrderService::ORDER_STATUS_BUYOUT_PAY) {//买断订单查询买断金
                $order['buyout_amount'] = OrderLease::where([['order_id', $order_id], ['status', OrderLease::ORDER_LEASE_STATUS_BUYOUT]])->sum('paid_rent');
            }
            $order_lease = OrderLease::where([['order_id', $order_id], ['which_period', 1]])->select('rent', 'paid_rent')->first();
            $order_lease = $order_lease ? $order_lease->toArray() : [];
            if (!empty($order_lease)) {
                $order['first_rent'] = $order_lease['rent'];
                $order['first_paid_rent'] = !empty($order_lease['paid_rent']) ? $order_lease['paid_rent'] : $order_lease['rent'];
                $order['paid_total_rent'] = OrderLease::where([['order_id', $order_id], ['status', OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('rent');
                $order['month_paid'] = OrderLease::where([['order_id', $order_id], ['status', OrderLease::ORDER_LEASE_STATUS_PAID]])->count();
                $order['last_term'] = $order['month_total'] - $order['month_paid'];
                $order['last_rent'] = OrderLease::where([['order_id', $order_id], ['status', '!=', OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('rent');
            } else {
                if ($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH) {//按月
                    $order['first_rent'] = sprintf("%01.2f", $order['lease_price'] * $order['amount']);//首期租金
                } elseif ($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY) {//按天
                    if ($order['order_lease_time'] <= 30) {
                        $order['first_rent'] = $order['rent_total'];
                    } else {
                        $order['first_rent'] = sprintf("%01.2f", $order['lease_price'] * 30 * 100 / 100 * $order['amount']);
                    }
                } elseif ($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM) {//自定义租期
                    $custom = GoodsCustomRent::where([['goods_id', $order['goods_id']], ['setmeal_id', $order['setmeal_id']], ['spec_id', $order['spec_id']], ['is_delete', GoodsService::GOODS_NO_DELETE_STATUS]])->select('which_period', 'lease_days', 'lease_price', 'withhold_cycle')->get();
                    $custom = $custom ? $custom->toArray() : [];
                    if (empty($custom)) {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期信息不存在');
                    } else {
                        $order['first_rent'] = sprintf("%01.2f", $custom[0]['lease_price'] * $order['amount']);//首期租金
                    }
                }
                $order['first_paid_rent'] = 0;
                $order['paid_total_rent'] = 0;
                $order['last_term'] = $order['month_total'];
                $order['last_rent'] = $order['rent_total'];
            }
            if ($order['is_renewal'] == self::ORDER_IS_RENEWAL) {//续租订单
                $parent_order = $this->where('trade_no', $order['parent_order_no'])->select('id')->first();
                $parent_order = obToArray($parent_order);
                $order['parent_order_id'] = $parent_order['id'];
            }
            if ($order['status'] == OrderService::ORDER_STATUS_RENEWAL_APP_PAY_SUCCESS) { //订单状态为续租完成，查询续租订单
                $sub_order = Order::where('parent_order_no', $order['trade_no'])->select('id', 'trade_no')->first();
                $sub_order = obToArray($sub_order);
                $order['sub_order_no'] = $sub_order['trade_no'];
                $order['sub_order_id'] = $sub_order['id'];
            }

            $authentic = AuthenticLog::where('order_id', $order_id)->value('status');
            $order['is_authentic'] = !empty($authentic) ? $authentic : 0;
            if (empty($authentic)) {
                $order['face_flow_id'] = 0;
            }


            unset($order['begin_time']);
            unset($order['end_time']);
            return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '获取成功', 'data' => $order];
        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单不存在', 'data' => []];
        }
    }

    public function orderCheckAutoPass($orderId)
    {
        if (!empty($orderId)) {
            OrderLog::addOrderLog($orderId, '', OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单审核通过');
            if (Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_SIGN_NOCHECK]])->exists()) {
                $order = Order::from('sp_order_2 as o')->where('o.id', $orderId)
                    ->leftjoin('sp_order_credit as c', 'c.order_id', 'o.id')
                    ->leftjoin('sp_member_2 as u', 'o.uid', 'u.id')
                    ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
                    ->select(
                        'o.id', 'o.mini_id', 'o.trade_no', 'o.begin_time', 'o.zulinbao_order_id', 'o.end_time', 'o.pact_url_3', 'o.uid',
                        'o.seller_id', 'o.is_insurance_choose', 'o.is_insurance_choose_custom',
                        'o.flow_id', 'o.mobile', 'o.user_email', 'o.sign_num', 'o.address', 'o.rent_total', 'o.month_total', 'o.amount',
                        'o.realname', 'o.rent_total','og.goods_name',
                        'o.foregift', 'o.status', 'o.prov', 'o.city', 'o.area', 'o.sign_status', 'o.is_rent_choose'
                        , 'c.platformLoanNo', 'o.create_time', 'og.lease_day'
                        , 'u.ant_user_id', 'u.mobile as user_mobile', 'u.id as x_user_id', 'u.cert_name', 'u.user_id', 'u.cert_no', 'u.esign_user_id'
                        , 'u.idcard_front', 'u.idcard_back', 'og.pact_type', 'og.is_buy_out', 'og.goods_title', 'og.setmeal_title', 'og.lease_set', 'og.setmeal_price', 'og.setmeal_foregift',
                        'og.goods_id', 'og.setmeal_id', 'og.id as order_goods_id', 'og.spec_id', 'og.lease_price', 'og.lease_time', 'og.website_price', 'og.start_date'
                        , 'su.mechanism', 'su.faname', 'su.shopname', 'su.contact_tel', 'su.company', 'su.company_area', 'su.companyid', 'su.id as shop_user_id'
                        , 'su.ant_user_id as mer_ant_id', 'u.openId'
                        , 'g.new_grade')
                    ->first();
                $order = $order ? $order->toArray() : [];

                if (!strstr($order['address'], '省') && !strstr($order['address'], '市')) {
                    $address = $order['prov'] . $order['city'] . $order['area'] . $order['address'];
                } else {
                    $address = $order['address'];
                }
                // if (mb_strlen($address) > 60) {
                //     return ReturnMsg(CommonService::HTTP_CODE_FAIL, '用户收货地址过长，请手动修改下');
                // }

                if($order['user_id']) {
                    //创建租赁平台订单
                    $res = AntchainAtoService::syncBehindOrder($order);
                    if ($res && $res['resultCode'] != 'OK') {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['resultMsg']);
                    }
                }


                $res = Order::where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_SIGN_NOTPAY]);

                if ($res) {
                    // 发送订单状态变更消息
                    SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_APPROVED,$orderId);

                    AlipayMessageService::sendChangeOrderLeaseMessage($orderId,AlipayMessageService::CONSUMER_FINANCE,'AUDIT_PASS');
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(1800);
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(86400);
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(86400*3);

                    return true;
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是待审核');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
    }

    //小程序未支付订单取消
    protected function noPayOrderCancel($order_id, $user_id, $member_id, $username = '')
    {
        if ($user_id) {
            $where[] = ['uid', $user_id];
        }
        if ($member_id) {
            $where[] = ['seller_id', $member_id];
        }
        $where[] = ['id', $order_id];
        //221017
        $order = $this->where($where)
            ->wherein('status', [OrderService::ORDER_STATUS_NOT_PAY, OrderService::ORDER_STATUS_SIGN_NOTPAY, OrderService::ORDER_STATUS_SIGN_NOCHECK, OrderService::ORDER_STATUS_PAY_SUCCESS])
            ->select('id', 'mini_id', 'uid', 'trade_no', 'rent_total', 'status', 'pay_type', 'rights_auth_no', 'alipay_trade_no', 'sign_status',
                'flow_id', 'create_time', 'sign_no')
            ->first();
        $order = $order ? $order->toArray() : [];
        if (empty($order)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单不存在', 'data' => []];
        }
        if ($order['status'] > OrderService::ORDER_STATUS_PAY_SUCCESS) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '当前订单状态不支持取消', 'data' => []];
        }

        if ($order['sign_no']) {
            AntchainAtoService::cancelWithholdPlan($order['trade_no']);
            AntchainAtoService::closeOrder($order['trade_no']);
            AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "AGREE", null, 0, null);
        }

        $miniId = $order['mini_id'];

        if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status'] <= OrderService::ORDER_STATUS_PAY_SUCCESS) {//解冻预授权，作废合同
            $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
            $alipay_data['authNo'] = $order['rights_auth_no'];
            $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
            if ($prequery['status']) {
                $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                    $thaw_data['amount'] = $rest_amount;
                    $thaw_data['authNo'] = $order['rights_auth_no'];
                    $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                    if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                        if (!empty($order['flow_id']) && $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING) {//合同未签署完成撤销
                            EsignService::revoke($order['flow_id']);
                        }
                        //查找扣款失败未履约的订单
                        $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                            ->groupBy('out_trade_no')
                            ->get();
                        foreach ($log as $value) {
                            $orderData = [
                                'orderId' => $value['order_no'],
                                'outTradeNo' => $value['out_trade_no'],
                                'tradeNo' => $value['trade_no'],
                                'status' => 'CLOSED',
                            ];
                            AlipayService::orderInfo($miniId, $orderData);
                        }
                        $user_order_count = Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                        Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count' => $user_order_count]);
                    } else {
                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '授权资金解冻失败，请联系平台客服解决', 'data' => []];
                    }
                }
            } else {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未查到授权资金解冻，请联系平台客服解决', 'data' => []];
            }
        }

        $order = Order::from('sp_order_2 as o')->where('o.id', $order_id)
            ->where('o.status', OrderService::ORDER_STATUS_PAY_SUCCESS)
            ->leftjoin('sp_shop_user_2 as s', 's.member_id', 'o.seller_id')
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->lockForUpdate()
            ->select('o.id as order_id', 'o.mini_id','o.pay_type', 'o.status', 'o.rent_total', 'o.rights_auth_no', 'o.trade_no',
                'o.alipay_trade_no', 'o.seller_id', 'o.month_total', 'o.uid', 'o.realname', 'o.order_from',
                'o.is_skip', 's.shop_balance', 'og.goods_title', 'o.payer_user_id', 'og.goods_id', 'm.mobile', 'm.cert_name',
               'o.pay_time', 's.refund_check', 's.shopname', 'o.flow_id', 'o.rights_auth_no', 'o.alipay_trade_no')->first();
        if ($order) {
            $res = OrderRefund::orderCloseAndRefund($order, $username);
            if ($res['status'] != 200) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '退款失败', 'data' => []];
            }
            SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_CANCELLED,$order_id);

        } else {
            $res = $this->where('id', $order_id)
                ->wherein('status', [OrderService::ORDER_STATUS_NOT_PAY, OrderService::ORDER_STATUS_SIGN_NOTPAY, OrderService::ORDER_STATUS_SIGN_NOCHECK, OrderService::ORDER_STATUS_PAY_SUCCESS])
                ->update(['status' => OrderService::ORDER_STATUS_CENCEL]);
            if($username){
                SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_REJECTED,$order_id);
            }

        }
        if ($res) {
            if (!empty($order['flow_id']) && $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING) {//合同未签署完成撤销
                EsignService::revoke($order['flow_id']);
            }
        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '取消失败', 'data' => []];
        }


        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '取消成功', 'data' => []];

    }


    //小程序未支付订单取消
    protected function noPayOrderBatchCancel($order_ids)
    {
//        $where[] = ['id','in',$order_id];
        //221017
//        $order_ids=explode(',',$order_ids);
        $orders = $this->wherein('id', $order_ids)
            ->where('status', OrderService::ORDER_STATUS_SIGN_NOCHECK)
            ->update(['status' => OrderService::ORDER_STATUS_CENCEL, 'update_time' => time()]);
        if ($orders) {
            return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '关闭订单成功', 'data' => []];
        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '取消失败', 'data' => []];
        }

    }


    //小程序未支付订单取消
    protected function noPayOrderSupplierCancel($order_id, $member_id)
    {

        $order = Order::from('sp_order_2 as o')
            ->select('o.id', 'o.mini_id', 'o.trade_no', 'o.uid', 'o.status', 'o.rights_auth_no', 'o.alipay_trade_no', 'o.flow_id', 'o.sign_status')
            ->where('o.seller_id', $member_id)
            ->where('o.id', $order_id)
            ->first();
        $order = obToArray($order);

        if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status'] <= OrderService::ORDER_STATUS_PAY_SUCCESS) {//解冻预授权，作废合同

            $miniId = $order['mini_id'];

            $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
            $alipay_data['authNo'] = $order['rights_auth_no'];
            $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
            if ($prequery['status']) {
                $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                    $thaw_data['amount'] = $rest_amount;
                    $thaw_data['authNo'] = $order['rights_auth_no'];
                    $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                    if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                        if (!empty($order['flow_id']) && $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING) {//合同未签署完成撤销
                            EsignService::revoke($order['flow_id']);
                        }
                        //查找扣款失败未履约的订单
                        $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                            ->groupBy('out_trade_no')
                            ->get();
                        foreach ($log as $value) {
                            $orderData = [
                                'orderId' => $value['order_no'],
                                'outTradeNo' => $value['out_trade_no'],
                                'tradeNo' => $value['trade_no'],
                                'status' => 'CLOSED',
                            ];
                            AlipayService::orderInfo($miniId, $orderData);
                        }
                    } else {
                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '授权资金解冻失败，请联系平台客服解决', 'data' => []];
                    }
                }
            } else {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未查到授权资金解冻，请联系平台客服解决', 'data' => []];
            }
        }
        $order = $this->where('id', $order_id)
            ->where('seller_id', $member_id)
            ->where('status', OrderService::ORDER_STATUS_SIGN_NOCHECK)
            ->update(['status' => OrderService::ORDER_STATUS_CENCEL, 'update_time' => time()]);
        if ($order) {
            return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '关闭订单成功', 'data' => []];
        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '取消失败', 'data' => []];
        }

    }


    //订单退款
    protected function orderRefund($order_id, $lease_id)
    {
        $order = $this->from('sp_order_2 as o')->where([['o.id', $order_id], ['o.status', OrderService::ORDER_STATUS_APPLY_REFUND]])
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->leftjoin('sp_shop_user_2 as s', 's.member_id', 'o.seller_id')
            ->select('o.id', 'o.mini_id', 'o.pay_type', 'o.status', 'o.rent_total', 'o.rights_auth_no', 'o.trade_no',
                'o.alipay_trade_no', 'o.seller_id', 'o.month_total', 'o.uid', 'o.order_from', 's.account', 's.account_type',
                's.shop_balance', 'og.goods_title', 'o.payer_user_id', 'og.goods_id', 'o.settlement_status',  'o.pay_time')
            ->first();
        $order = $order ? $order->toArray() : [];
        if (!empty($order)) {
            $miniId = $order['mini_id'];

            if ($order['pay_type'] == OrderLease::LEASE_PAY_TYPE_HUABEI) {//花呗代扣
                $refund_data['amount'] = $order['paid_rent'];
                $refund_data['outTradeNo'] = $order['trade_no'];
                $refund_data['tradeNo'] = $order['alipay_trade_no'];
                $refund_res = AlipayService::alipayRefund($miniId, $refund_data);
                if ($refund_res['status']) { //退款成功
                    $res = ShopTrans::addHuabeiOrderRefundTrans($order, $refund_res['data']['alipay_trade_no']);
                    if ($res) {

                        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '退款成功', 'data' => []];
                    } else {
                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '退款失败', 'data' => []];
                    }
                } else {
                    return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '花呗退款失败', 'data' => []];
                }
            } else {
                $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                $alipay_data['authNo'] = $order['rights_auth_no'];
                $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
                if ($prequery['status']) {
                    $lease_arr = explode(',', $lease_id);
                    foreach ($lease_arr as $k => $v) {
                        $order_lease = OrderLease::where([['id', $v], ['order_id', $order_id]])
                            ->select('which_period', 'rent', 'paid_rent', 'settle_type', 'out_order_no')->first();
                        $order_lease = $order_lease ? $order_lease->toArray() : [];
                        if (!empty($order_lease)) {
                            $refund_data['amount'] = $order_lease['paid_rent'];
                            $refund_data['outTradeNo'] = $order_lease['out_order_no'];
                            $refund_data['tradeNo'] = $order['trade_no'] . '|' . $v;
                            $refund_res = AlipayService::alipayRefund($miniId, $refund_data);
                            if ($refund_res['status']) { //退款成功
                                ShopTrans::addOrderRefundTrans($order, $order_lease, $refund_res['data']['alipay_trade_no']);
                            }
                        } else {
                            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '账单不存在', 'data' => []];
                        }
                    }
                    $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                    if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                        $thaw_data['amount'] = $rest_amount;
                        $thaw_data['authNo'] = $order['rights_auth_no'];
                        $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                        if ($thaw_query['status'] && $thaw_query['data']['status'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                            return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '退款成功', 'data' => []];
                        } else {
                            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '退款失败', 'data' => []];
                        }
                    } else {
                        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '退款成功', 'data' => []];
                    }
                } else {
                    return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单预授权查询失败', 'data' => []];
                }
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 后台总订单归类组装数据统计
     * @param $data
     * @return int[]
     */
    protected function computeStatus($request, $where = [], $username = '', $sale_user_id = '')
    {

        // $orderStatus = $request->input('orderStatus','');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $receivingMobile = $request->input('receivingMobile', '');
        $riskName = $request->input('riskName', '');
        $riskMobile = $request->input('riskMobile', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $card = $request->input('card', '');
        $roleId = $request->input('role_id', '');
        $orderStatus = $request->input('orderStatus', '');
        $sale_user_id_order = $request->input('sale_user_id', '');
        $order_fixed = $request->input('order_fixed', '');
        $dlz_risk_level= $request->input('dlz_risk_level', '');
        $deviceNumber = $request->input('deviceNumber', '');

        if ($sale_user_id_order && !is_array($sale_user_id_order)) {
            $where[] = ['o.sale_user_id', $sale_user_id_order];
        }

        if ($order_fixed) {
            $where[] = ['o.order_fixed', $order_fixed];
        }

        if ($username) {
            $where[] = ['o.username', $username];
        }


        if ($deviceNumber) {
            $where[] = ['og.device_number', $deviceNumber];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }

        if ($orderStatus) {
            if ($roleId == 54 && $orderStatus == OrderService::ORDER_STATUS_REPAYMENT) {
                $where[] = ['o.status', OrderService::ORDER_STATUS_REPAYMENT];
            } else if ($roleId == 54 && $orderStatus == OrderService::ORDER_STATUS_OVERDUE) {
                $where[] = ['o.status', OrderService::ORDER_STATUS_OVERDUE];
            } else {
                $where[] = ['o.status', $orderStatus];
            }
        }
        if ($roleId == 54) {
            $where[] = ['o.status', OrderService::ORDER_STATUS_OVERDUE];
        }

        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($receivingMobile) {
            $where[] = ['o.mobile', $receivingMobile];
        }
        if ($riskName) {
            $where[] = ['m.cert_name', 'like', '%' . $riskName . '%'];
        }
        if ($sale_user_id && count(explode(',', $sale_user_id)) <= 1) {
            $where[] = ['o.sale_user_id', $sale_user_id];
        }
        if ($riskMobile) {
            $where[] = ['m.mobile', $riskMobile];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', $shopName];
        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }
        if ($card) {
            $where[] = ['m.cert_no', 'like', $card . '%'];
        }


        $count = [
            OrderService::ORDER_LIST_STATUS_ALL => 0, //全部订单
            OrderService::ORDER_LIST_STATUS_NOT_CHECK => 0, //待审核
            OrderService::ORDER_LIST_STATUS_NOT_PAY => 0, //待付款订单
            OrderService::ORDER_LIST_STATUS_NOT_RISK => 0, //待风控订单
            OrderService::ORDER_LIST_STATUS_DELIVERED_NOT => 0, //待发货订单
            OrderService::ORDER_LIST_STATUS_DELIVERED_IS => 0, //已发货订单
            OrderService::ORDER_LIST_STATUS_ING => 0, //租用中订单
            OrderService::ORDER_LIST_STATUS_COMPLETED => 0, //交易完成订单
            OrderService::ORDER_LIST_STATUS_CANCEL => 0, //取消订单
            OrderService::ORDER_LIST_STATUS_RETURN => 0, //退货订单
            OrderService::ORDER_LIST_STATUS_BUY_OUT => 0, //买断订单
            OrderService::ORDER_LIST_STATUS_RENEWAL => 0, //续租订单
            OrderService::ORDER_LIST_STATUS_REFUND => 0, //退款订单
        ];

        $sale_user_ids = [];
        if ($sale_user_id && count(explode(',', $sale_user_id)) > 1) {
            $sale_user_ids = explode(',', $sale_user_id);
        }
        if ($sale_user_id_order && is_array($sale_user_id_order)) {
            $sale_user_ids = $sale_user_id_order;
        }
        $seller_ids = $request->input('seller_id', '');
        if($dlz_risk_level){
            $order_ids=OrderDlzwRisk::where('risk_level',$dlz_risk_level)->pluck('order_id')->toArray();
        }
        $status = OrderService::getOrderStatus('', true);
        foreach ($status as $key => $value) {
            //$key是tabs $value是status的值
            if($orderPayTime){
                $wherea=[];
                $orderRentPayTimea = explode('~', $orderPayTime);
                $wherea[] = ['pay_time', '>=', strtotime($orderRentPayTimea[0])];
                $wherea[] = ['pay_time', '<=', strtotime($orderRentPayTimea[1])];

                $order_ids=OrderLease::query()->where($wherea)->groupBy('order_id')->pluck('order_id');

                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->whereIn('o.id', $order_ids)
                    ->where($where)->count();

            }else if ($dlz_risk_level) {
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->whereIn('o.id', $order_ids)
                    ->where($where)->count();
            }else if ($seller_ids) {
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->whereIn('o.seller_id', $seller_ids)
                    ->where($where)->count();
            }else if($roleId == 93){
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', [OrderService::ORDER_STATUS_PAY_SUCCESS, OrderService::ORDER_STATUS_DELIVER_SUCCESS])
                    ->whereIn('o.status', $value)
                    ->where($where)->count();
            } else if ($sale_user_ids) {
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->whereIn('o.sale_user_id', $sale_user_ids)
                    ->where($where)->count();
            } else   if ($roleId == 94) {
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->whereIn('o.status', [OrderService::ORDER_STATUS_REPAYMENT, OrderService::ORDER_STATUS_OVERDUE])
                    ->where($where)->count();
            }else {
                $count[$key] = $this->from('sp_order_2 as o')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->whereIn('o.status', $value)
                    ->where($where)->count();
            }


        }

        return $count;
    }

    /**
     * 后台总订单归类组装数据统计成功订单
     * @param $data
     * @return int[]
     */
    public static function computeStatusSuccess($data, $count = [])
    {
        if (!$count) {
            $count = [
                OrderService::ORDER_LIST_STATUS_SUCCESS_ALL => 0, //全部订单
                OrderService::ORDER_LIST_STATUS_DELIVERED_NOT => 0, //待发货订单
                OrderService::ORDER_LIST_STATUS_DELIVERED_IS => 0, //已发货订单
                OrderService::ORDER_LIST_STATUS_ING => 0, //租用中订单
                OrderService::ORDER_LIST_STATUS_COMPLETED => 0, //交易完成订单
                OrderService::ORDER_LIST_STATUS_CANCEL => 0, //取消订单
                OrderService::ORDER_LIST_STATUS_RETURN => 0, //退货订单
                OrderService::ORDER_LIST_STATUS_BUY_OUT => 0, //买断订单
                OrderService::ORDER_LIST_STATUS_RENEWAL => 0, //续租订单
                OrderService::ORDER_LIST_STATUS_REFUND => 0, //退款订单
            ];
        }
        $status = OrderService::getOrderStatus('', true);
        unset($status[OrderService::ORDER_LIST_STATUS_SUCCESS_ALL]);
        foreach ($data as $item) {
            foreach ($status as $key => $value) {
                $res = strstr($key, '-notList');
                if (!$res) {
                    if (in_array($item['status'], $value) && isset($count[$key])) {
                        $count[$key] += $item['count'];
                    }
                }
            }
            $count[OrderService::ORDER_LIST_STATUS_SUCCESS_ALL] += $item['count'];
        }
        return $count;
    }


    /**
     * 通过ID检测订单是否存在
     * @param $id
     * @param string $seller_id
     * @return bool
     */
    public static function checkOrderById($id, $seller_id = '')
    {
        $flag = false;
        $where['id'] = $id;

        if ($seller_id != '1704471738' && $seller_id) {
            $where['seller_id'] = $seller_id;
        }

        $order = Order::where($where)->select('id')->first();
        $order = obToArray($order);

        if ($order) {
            $flag = true;
        }
        return $flag;
    }

    /**
     * 通过订单号检测订单是否存在
     * @param $no
     * @param string $seller_id
     * @return bool
     */
    public static function checkOrderByNo($no, $seller_id = '')
    {
        $flag = false;
        $where['trade_no'] = $no;
        if ($seller_id) {
            $where['seller_id'] = $seller_id;
        }
        $order = Order::where($where)->select('id')->first();
        $order = obToArray($order);
        if ($order) {
            $flag = true;
        }
        return $flag;
    }

    public static function checkOrderOverdueStatus($id)
    {
        $orderStatus = '';
        //检测账单是都有逾期的
        $checkLease = OrderLease::where(['order_id' => $id, 'status' => OrderLease::ORDER_LEASE_STATUS_OVERDUE])->select('id')->get();
        $checkLease = obToArray($checkLease);
        if ($checkLease) {
            //有逾期的账单
            $orderStatus = OrderService::ORDER_STATUS_OVERDUE;
        } else {
            //无逾期的订单
            $order = Order::where('id', $id)->select('status')->first();
            $order = obToArray($order);
            if ($order) {
                if ($order['status'] == OrderService::ORDER_STATUS_OVERDUE || $order['status'] == OrderService::ORDER_STATUS_REPAYMENT) {
                    $orderStatus = OrderService::ORDER_STATUS_CONFIRM_GOODS;
                } else {
                    $orderStatus = $order['status'];
                }
            }
        }

        $checkLeaseid = OrderLease::where(['order_id' => $id, 'status' => ['<>', '1']])->count();
        $pact_type = OrderGoods::where('order_id', $id)->value('pact_type');
        if ($checkLeaseid <= 0 && $pact_type == 2) {
            $rent = OrderLease::where(['order_id' => $id])->sum('rent');
            $paid_rent = OrderLease::where(['order_id' => $id])->sum('paid_rent');
            if ($paid_rent >= $rent) {
                SendChangeOrderMessage::dispatch($id,AlipayMessageService::CONSUMER,'FINISH');
                SendChangeOrderMessage::dispatch($id,AlipayMessageService::KX_SHOPPING,'FINISHED');

                $orderStatus = OrderService::ORDER_STATUS_COMPLETED;
                $add = [
                    'uid' => 23,
                    'username' => '系统',
                    'create_time' => time(),
                    'remark' => '还款完成，订单完成',
                    'order_id' => $id
                ];
                OrderRemark::insert($add);
            }
        }


        return $orderStatus;
    }

    /**
     * 订单列表
     * @param $request
     * @param array $where
     * @return array
     */
    public static function orderList($request, $where = [], $username = '', $sale_user_id = '')
    {
        $mini_id = $request->input('mini_id', '');
        $biz_type = $request->input('biz_type', '');

        $orderStatus = $request->input('orderStatus', '');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $receivingMobile = $request->input('receivingMobile', '');
        $riskName = $request->input('riskName', '');
        $card = $request->input('card', '');
        $riskMobile = $request->input('riskMobile', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $orderStatusGroup = $request->input('orderStatusGroup', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $is_handle = $request->input('is_handle');
        $roleId = $request->input('role_id', '');
        $deviceNumber = $request->input('deviceNumber', '');
        $sale_user_id_order = $request->input('sale_user_id', '');
        $seller_ids = $request->input('seller_id', '');
        $order_fixed = $request->input('order_fixed', '');
        $dlz_risk_level=$request->input('dlz_risk_level', '');


        if ($is_handle) {
            $where[] = ['o.is_handle', $is_handle];
        }
        // 小程序
        if ($mini_id) {
            $where[] = ['o.mini_id', $mini_id];
        }
        // 业务类型
        if ($biz_type) {
            $where[] = ['o.biz_type', $biz_type];
        }

//        $username = $request->input('username','');
        if ($order_fixed) {
            $where[] = ['o.order_fixed', $order_fixed];
        }
        if ($username) {
            $where[] = ['o.username', $username];
        }

        if ($sale_user_id_order && !is_array($sale_user_id_order)) {
            $where[] = ['o.sale_user_id', $sale_user_id_order];
        }

        if ($sale_user_id && count(explode(',', $sale_user_id)) <= 1) {
            $where[] = ['o.sale_user_id', $sale_user_id];
        }

        $countWhereIn = [];
        if ($orderStatus) {
            if ($roleId && $orderStatus == OrderService::ORDER_STATUS_REPAYMENT) {
                $where[] = ['o.status', OrderService::ORDER_STATUS_REPAYMENT];
            } else if ($roleId && $orderStatus == OrderService::ORDER_STATUS_OVERDUE) {
                $where[] = ['o.status', OrderService::ORDER_STATUS_OVERDUE];
            } else {
                $where[] = ['o.status', $orderStatus];
            }
        }


        if ($orderStatusGroup) {
            $countWhereIn = OrderService::getOrderStatus($orderStatusGroup);
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($receivingMobile) {
            $where[] = ['o.mobile', $receivingMobile];
        }
        if ($riskName) {
            $where[] = ['m.cert_name', 'like', '%' . $riskName . '%'];
        }

        if ($riskMobile) {
            $where[] = ['m.mobile', $riskMobile];
        }
//        if ($shopName) {
//            $where[] = ['s.shopname', 'like', $shopName];
//        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }
        if ($card) {
            $where[] = ['m.cert_no', 'like', $card . '%'];
        }

        if ($deviceNumber) {
            $where[] = ['og.device_number', $deviceNumber];
        }

//       $where[] = ['og.device_number', '=',null];
        $orderList = Order::from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select(
                'o.id', 'o.mini_id', 'o.biz_type', 'o.uid', 'o.username', 'o.status', 'm.openId', 'o.location', 'o.phone_brand', 'o.is_credit_select', 'o.is_credit_up', 'o.is_insurance_choose',
                'o.is_insurance_choose_custom','og.pay_cash_pledge',  'o.is_rent_choose', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.amount', 'o.pay_type', 'o.foregift', 'o.foregift_deduct', 'o.foregift_pay', 'o.is_apply_goods'
                , 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.sign_status', 'o.guarantee_status', 'o.pact_url', 'o.is_skip', 'o.order_from'
                , 'o.prov', 'o.city', 'o.area', 'o.begin_time', 'o.end_time', 'o.create_time', 'o.rights_auth_no',  'o.alipay_trade_no', 'o.is_abnormal'
                , 'o.is_renewal', 'o.parent_order_no', 'o.emergency_contact', 'o.seller_id',  'o.sale_user_id', 'm.level', 'og.cash_pledge', 'og.household_address'
                , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type', 'og.setmeal_foregift', 'og.setmeal_price'
                , 'm.mobile', 'm.cert_name', 'm.cert_no', 'm.openId', 'm.idcard_front', 'm.idcard_back', 'm.gender', 'og.website_price', 'o.is_lock', 'og.acquisition_price'
                , 'm.education', 'g.new_grade', 'og.lease_set', 'og.lease_day', 'og.down_payment', 'o.is_latest_performance_time', 'm.stable_wealth', 'm.contract_no'
                , 'o.reduced_status', 'o.reduced_price', 'm.from', 'm.level_performance', 'm.minutes', 'o.prepayment_total', 'm.certify_id','o.scene','o.withhold_status','og.transaction_fee'
            )
            ->where($where);

        if($orderPayTime){
            $wherea=[];
            $orderRentPayTimea = explode('~', $orderPayTime);
            $wherea[] = ['pay_time', '>=', strtotime($orderRentPayTimea[0])];
            $wherea[] = ['pay_time', '<=', strtotime($orderRentPayTimea[1])];

            $order_ids=OrderLease::query()->where($wherea)->groupBy('order_id')->pluck('order_id');
            $orderList->whereIn('o.id', $order_ids);
        }
        if($dlz_risk_level){
            $order_ids=OrderDlzwRisk::where('risk_level',$dlz_risk_level)->pluck('order_id')->toArray();
            $orderList->whereIn('o.id', $order_ids);
        }

        if ($roleId == 94) {
            $orderList->whereIn('o.status', [OrderService::ORDER_STATUS_REPAYMENT, OrderService::ORDER_STATUS_OVERDUE]);
        }
        if ($roleId == 93) {
            $orderList->whereIn('o.status', [OrderService::ORDER_STATUS_PAY_SUCCESS, OrderService::ORDER_STATUS_DELIVER_SUCCESS]);
        }

        if ($sale_user_id && count(explode(',', $sale_user_id)) > 1) {
            $orderList->whereIn('o.sale_user_id', explode(',', $sale_user_id));
        }
        if ($sale_user_id_order && is_array($sale_user_id_order)) {
            $orderList->whereIn('o.sale_user_id', $sale_user_id_order);
        }
        if ($seller_ids && is_array($seller_ids)) {
            $orderList->whereIn('o.seller_id', $seller_ids);
        }
        $countWhereIn && $orderList->whereIn('o.status', $countWhereIn);
        $orderList->orderBy('o.create_time', 'desc');
        $list = obToArray($orderList->paginate($pageSize));


        if (isset($list['data'])) {
            foreach ($list['data'] as $k => $value) {

                $list['data'][$k]['dlz_result']=OrderDlzwRisk::getUserDLzwRisk($value['id']);

                $list['data'][$k]['scene_dec'] = AlipayScene::where('scene',$value['scene'])->value('dec');
                $list['data'][$k]['shopname'] = ShopUser::query()->where('member_id',$value['seller_id'])->value('shopname');

                //订单状态
                $list['data'][$k]['address'] = AddressRemoveRepeat($value['prov'], $value['city'], $value['area'], $value['address']);
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$value['status']];
                $list['data'][$k]['create_time'] = dateFormat($value['create_time']);


                $stable_wealth = json_decode($value['stable_wealth'], true);
                if (is_array($stable_wealth)) {
                    if (isset($stable_wealth['data']) && $stable_wealth['data']['income_model']) {
                        $income_model = $stable_wealth['data']['income_model'];
                        $income_model_desc = 0;
                        if ($income_model <= 19) {
                            $income_model_desc = '0-1500';
                        } else if ($income_model > 19 && $income_model < 30) {
                            $income_model_desc = '1500-3000';
                        } else if ($income_model >= 30 && $income_model <= 39) {
                            $income_model_desc = '3000-4500';
                        } else if ($income_model >= 40 && $income_model <= 49) {
                            $income_model_desc = '3000-4500';
                        } else if ($income_model >= 50 && $income_model <= 59) {
                            $income_model_desc = '4500-6000';
                        } else if ($income_model >= 60 && $income_model <= 69) {
                            $income_model_desc = '8000-10000';
                        } else if ($income_model >= 70 && $income_model <= 79) {
                            $income_model_desc = '10000-13000';
                        } else if ($income_model >= 80 && $income_model <= 89) {
                            $income_model_desc = '13000-16000';
                        } else if ($income_model >= 90 && $income_model <= 100) {
                            $income_model_desc = '16000-20000';
                        }
                    }
                    if (isset($stable_wealth['data']) && $stable_wealth['data']['stable_model']) {
                        $stable_model = $stable_wealth['data']['stable_model'];
                        $stable_model_desc = 0;
                        if ($stable_model <= 19) {
                            $stable_model_desc = '无法预测';
                        } else if ($stable_model >= 20 && $stable_model < 39) {
                            $stable_model_desc = '0-6';
                        } else if ($stable_model >= 40 && $stable_model <= 59) {
                            $stable_model_desc = '6-12';
                        } else if ($stable_model >= 60 && $stable_model <= 79) {
                            $stable_model_desc = '12-18';
                        } else if ($stable_model >= 80 && $stable_model <= 100) {
                            $stable_model_desc = '18-24';
                        }
                    }
                    if (isset($stable_wealth['data']) && $stable_wealth['data']['historical_pattern']) {
                        $historical_pattern = $stable_wealth['data']['historical_pattern'];
                        $historical_pattern_desc = 0;
                        if ($historical_pattern <= 9) {
                            $historical_pattern_desc = '无法预测';
                        } else if ($historical_pattern >= 10 && $historical_pattern <= 19) {
                            $historical_pattern_desc = '0-6';
                        } else if ($historical_pattern >= 20 && $historical_pattern <= 29) {
                            $historical_pattern_desc = '6-12';
                        } else if ($historical_pattern >= 30 && $historical_pattern <= 39) {
                            $historical_pattern_desc = '12-24';
                        } else if ($historical_pattern >= 40 && $historical_pattern <= 49) {
                            $historical_pattern_desc = '24-36';
                        } else if ($historical_pattern >= 50 && $historical_pattern <= 59) {
                            $historical_pattern_desc = '36-48';
                        } else if ($historical_pattern >= 60 && $historical_pattern <= 69) {
                            $historical_pattern_desc = '48-60';
                        } else if ($historical_pattern >= 70 && $historical_pattern <= 79) {
                            $historical_pattern_desc = '60-84';
                        } else if ($historical_pattern >= 80 && $historical_pattern <= 89) {
                            $historical_pattern_desc = '84-120';
                        } else if ($historical_pattern >= 90 && $historical_pattern <= 100) {
                            $historical_pattern_desc = '120-180';
                        }
                    }
                    $list['data'][$k]['stable_wealth'] = isset($stable_wealth['data']) ? '金融能力' . $income_model_desc . '；稳定指数预测' . $stable_model_desc . '；历史属性指数预测' . $historical_pattern_desc : $stable_wealth['msg'];
                }
                $list['data'][$k]['education'] = $value['education'];
                $list['data'][$k]['pact_type_name'] = GoodsService::getGoodsPactName($value['pact_type']);
                if ($value['pact_type'] == GoodsService::GOODS_PACT_TYPE_FIXED) {
                    $setmeal_price = $value['setmeal_price'] >= 1 ? $value['setmeal_price'] : 0.00;
                    $list['data'][$k]['setmeal_price'] = $setmeal_price;
                    $list['data'][$k]['setmeal_pricea'] = $setmeal_price;
                } else {
                    $list['data'][$k]['setmeal_price'] = 0;
                    $list['data'][$k]['setmeal_pricea'] = 0;
                }
                //订单来源
                $source = Source::where(['source_code' => $value['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                $shopRate = OrderRate::where(['order_id' => $value['id']])->value('shop_rate');
                if ($value['order_from'] == 'saleOnline' && $value['openId']) {
                    $source = $source . '-微信';
                }
                if ($value['order_from'] == 'saleOnline' && empty($value['openId'])) {
                    $source = $source . '-支付宝';
                }
                if ($value['contract_no']) {
                    $source = $source . '-W';
                }
                if ($value['from']) {
                    $source = $source . '1';
                }


                $list['data'][$k]['merchant_contribute'] = OtherWithholdLog::where('order_no', $value['trade_no'])->where('status', 1)->sum('merchant_contribute');

                $shopRate = !empty($shopRate) ? "(" . $shopRate . "%)" : '';
                $source = $source . $shopRate;
                $channel_name = SaleUser::where('sale_user_id', $value['sale_user_id'])->value('channel_name');
                if ($channel_name) {
                    $source = $source . '-' . $channel_name;
                }
                $list['data'][$k]['source'] = $source;
                //新旧程度
                $list['data'][$k]['new_grade_title'] = GoodsService::getGoodsNewGrade($value['new_grade']);
                //风控信息
                $list['data'][$k]['risk'] = '';
                $list['data'][$k]['risk_report_url'] = '';
                if ($value['is_skip'] == Order::RISK_SKIP_NOT) {
                    $risk = RiskCredit::getRiskCredit($value['id']);
                    if ($risk) {
                        $list['data'][$k]['risk'] = '验证分' . $risk['verification_score'] . ';欺诈分' . $risk['cheat_score'] . ';' . $risk['final_decision'];
                        $list['data'][$k]['risk_report_url'] = $risk['risk_report_url'];
                    }
                }
                //实名认证
//                $authenticLog = AuthenticLog::where(['order_id' => $value['id'], 'status' => AuthenticLog::AUTHENTIC_STATUS_PASS])->select('status')->first();
                $list['data'][$k]['authentic'] = [
                    'age' => getAgeByID($value['cert_no']),
                    'sex' => get_sex($value['cert_no']),
                    'status' => $value['certify_id'] ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                ];
                //物流信息
                $list['data'][$k]['logistic'] = [];
                if ($value['status'] >= OrderService::ORDER_STATUS_DELIVER_SUCCESS||$value['status']==OrderService::ORDER_STATUS_REFUND_SUCCESS) {
                    $logistics = Logistics::where(['order_id' => $value['id'], 'type' => Logistics::EXPRESS_TYPE_SEND])->select('logistics_name', 'logistics_no', 'delivery_type', 'status')->first();
                    $list['data'][$k]['logistic'] = $logistics ? obToArray($logistics) : [];
                }


                $log = OrderLease::getLeaseData($value['id'], $value['trade_no']);
                //租金 下期待付款

                if ($value['reduced_status'] == 1) {
                    $log['count']['paid_rent'] = bcadd($log['count']['paid_rent'], $value['reduced_price'], 2);
                }

                $list['data'][$k]['lease'] = $log['count'];


                //流水记录
                $list['data'][$k]['leaseFlow'] = $log['lease_log'];
                //客服备注
                $list['data'][$k]['orderRemark'] = OrderRemark::getRemark($value['id']);
                $list['data'][$k]['orderRemarkTwo'] = OrderRemark::getRemarkTwo($value['id']);

                if ($value['pact_url'] && $value['openId']) {
                    $list['data'][$k]['pact_url'] = $value['trade_no'] . '.pdf';
                }
                //退款原因
                $list['data'][$k]['orderRefundReason'] = '';
                if (in_array($value['status'], OrderService::getOrderStatus(OrderService::ORDER_REFUND_STATUS))) {
                    $list['data'][$k]['orderRefundReason'] = OrderRefund::where(['order_id' => $value['id']])->value('refund_reason');
                }

                $list['data'][$k]['is_insurance_name'] = GoodsService::getGoodsInsuranceName($value['is_insurance_choose']) . ($value['is_insurance_choose'] == 100 ? $value['is_insurance_choose_custom'] : '');

                $alipayReiskb = MemberAlipayRiskCredit::query($value['uid']);
                $list['data'][$k]['risk_credit_result'] = $alipayReiskb;

                $list['data'][$k]['qnp_result'] = MemberQnRisk::query($value['uid']);

                $alipayReiska = MemberAlipayRisk::query($value['uid']);
                if ($alipayReiska) {
                    foreach ($alipayReiska as $keya => $alipayReisk) {
                        $result = json_decode($alipayReisk['result'], true);
                        $result['risk_desc'] = str_replace('风险', '', $result['risk_desc']);
                        foreach ($result['sub_risk_result_list'] as &$va) {
                            $va['risk_desc'] = str_replace('风险', '', $va['risk_desc']);
                        }
                        $result['create_time'] = date('Y-m-d H:i', $alipayReisk['create_time']);
                        $list['data'][$k]['risk_result'][] = $result;
                    }

                }
//                $list['data'][$k]['cert_no'] = substr_replace($value['cert_no'], '**********', 3, 15);;


            }
            if ($request['role_id'] != 1&&$request['role_id'] != 92&&$request['role_id'] != 94&&$request['role_id'] != 91) {
                foreach ($list['data'] as $k => $value) {
                    //订单状态
                    $list['data'][$k]['authentic'] = [
                        'age' =>'',
                        'sex' =>'',
                        'status' => $value['certify_id'] ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                    ];
//                    $list['data'][$k]['address_mobile'] = substr_replace($value['address_mobile'], '****', 3, 4);
//                    $list['data'][$k]['address'] = '******';
//                    $list['data'][$k]['area'] = '******';
//                    $list['data'][$k]['realname'] = mb_substr($value['realname'], 0, 1, 'utf-8') . '*' . mb_substr($value['cert_name'], 2, 6, 'utf-8');
                    $list['data'][$k]['mobile'] = substr_replace($value['mobile'], '****', 3, 8);
//                    $list['data'][$k]['cert_name'] = mb_substr($value['cert_name'], 0, 1, 'utf-8') . '*' . mb_substr($value['cert_name'], 2, 6, 'utf-8');
                    $list['data'][$k]['cert_no'] = substr_replace($value['cert_no'], '**********', 3, 15);;
                }
            }

        }


        return ['list' => $list];
    }

    /**
     * 订单详情
     * @param $request
     * @param array $where
     * @return array
     */
    public static function orderDetail($orderId, $member_id = '', $username = '')
    {

        $orderList = Order::from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select(
                'o.id', 'o.uid', 'o.status', 'o.is_credit_select', 'o.is_credit_up', 'o.is_insurance_choose', 'o.is_insurance_choose_custom',  'o.is_rent_choose', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.amount', 'o.pay_type', 'o.foregift', 'o.foregift_deduct', 'o.foregift_pay'
                , 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.sign_status', 'o.guarantee_status', 'o.pact_url', 'o.is_skip', 'o.order_from'
                , 'o.prov', 'o.city', 'o.area', 'o.begin_time', 'o.end_time', 'o.create_time', 'o.rights_auth_no',  'o.is_abnormal'
                , 'o.is_renewal', 'o.parent_order_no', 'o.emergency_contact', 'o.seller_id',  'o.sale_user_id'
                , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type', 'og.setmeal_foregift', 'og.setmeal_price'
                , 'm.mobile', 'm.cert_name', 'm.cert_no', 'm.idcard_front', 'm.idcard_back', 'm.gender'
                , 's.shopname'
                , 'g.new_grade'
            )
            ->where('o.username', $username)
            ->where('o.id', $orderId)
            ->where('o.is_handle', '2')
            ->first();
        $orderList = obToArray($orderList);
        // dd($orderList);
        if (!empty($orderList)) {

            //免押金额
            $orderList['all_foregift'] = sprintf("%01.2f", $orderList['foregift'] + $orderList['foregift_deduct']);
            $orderList['part_foregift'] = sprintf("%01.2f", $orderList['foregift'] + $orderList['foregift_deduct'] - $orderList['foregift_pay']);


            //新旧程度
            $orderList['new_grade_title'] = GoodsService::getGoodsNewGrade($orderList['new_grade']);

            //订单状态
            $orderList['address'] = AddressRemoveRepeat($orderList['prov'], $orderList['city'], $orderList['area'], $orderList['address']);

            $orderList['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$orderList['status']];
            // $list['data'][$k]['statusName'] = '';

            $orderList['create_time'] = dateFormat($orderList['create_time']);
            $orderList['pact_type'] = GoodsService::getGoodsPactName($orderList['pact_type']);
            $orderList['pact_type_number'] = $orderList['pact_type'];
            if ($orderList['pact_type'] == GoodsService::GOODS_PACT_TYPE_FIXED) {
                $setmeal_price = $orderList['setmeal_price'] >= 1 ? $orderList['setmeal_price'] : 0.00;
                $orderList['setmeal_price'] = $setmeal_price;
            } else {
                $orderList['setmeal_price'] = 0;
            }

            //订单来源
            $source = Source::where(['source_code' => $orderList['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
            $shopRate = OrderRate::where(['order_id' => $orderList['id']])->value('shop_rate');
            $shopRate = !empty($shopRate) ? "(" . $shopRate . "%)" : '';
            $orderList['source'] = $source . $shopRate;

            $uid = $orderList['uid'];
            $userData = obToArray(MemberOther::where('id', $uid)->select('cert_name', 'cert_no', 'province', 'city as user_city', 'idcard_back', 'idcard_front')->first());
            $cert_no = isset($userData['cert_no']) ? $userData['cert_no'] : '';
            $authenticLog = obToArray(AuthenticLog::where(['cert_no' => $cert_no])->select('status', 'cert_name', 'idcard_back', 'idcard_front')->first());
            // if($authenticLog){
            $orderList['authentic'] = [
                'age' => getAgeByID($cert_no),
                'sex' => get_sex($cert_no),
                'status' => $authenticLog ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                'cert_name' => $userData['cert_name'],
                'cert_no' => $cert_no,
                'idcard_back' => $userData['idcard_back'],
                'idcard_front' => $userData['idcard_front'],
                'user_city' => $userData['user_city'],
                'province' => $userData['province'],
            ];
            // }


            //物流信息
            $orderList['logistic'] = [];
            if ($orderList['status'] >= OrderService::ORDER_STATUS_DELIVER_SUCCESS||$orderList['status']==OrderService::ORDER_STATUS_REFUND_SUCCESS) {
                $logistics = Logistics::where(['order_id' => $orderList['id'], 'type' => Logistics::EXPRESS_TYPE_SEND])->select('logistics_name', 'logistics_no', 'delivery_type', 'status')->first();
                $orderList['logistic'] = $logistics ? obToArray($logistics) : [];
            }
            $log = OrderLease::getLeaseData($orderList['id'], $orderList['trade_no']);
            //租金 下期待付款
            $orderList['lease'] = $log['count'];
            // $list['data'][$k]['lease'] = 11;
            //流水记录
            $orderList['leaseFlow'] = $log['lease_log'];

            $member_arr = [$member_id, 0];
            $username = NewAdmin::whereIn('user_id', $member_arr)->select('username')->get();
            $username = obToArray($username);
            if ($username) {
                $usernames = array_column($username, 'username');
            }

            $remark = OrderRemark::where(['order_id' => $orderId])->whereIn('username', $usernames)->select('username', 'create_time', 'remark')->orderBy('id', 'desc')->get();
            $remark = obToArray($remark);
            if ($remark) {
                foreach ($remark as $k => $v) {
                    $remark[$k]['create_time'] = dateFormat($v['create_time']);
                }
            }
            $orderList['orderRemark'] = $remark;


            //退款原因
            $orderList['orderRefundReason'] = '';
            if (in_array($orderList['status'], OrderService::getOrderStatus(OrderService::ORDER_REFUND_STATUS))) {
                $orderList['orderRefundReason'] = OrderRefund::where(['order_id' => $orderList['id']])->value('refund_reason');
            }
            //租期详情
            $lease_list = OrderLease::where('order_id', $orderList['id'])
                ->select('id', 'which_period', 'rent', 'begin_time', 'end_time', 'status', 'pay_time', 'alipay_trade_no', 'withhold_status', 'pay_type')
                ->get();
            $lease_list = obToArray($lease_list);
            foreach ($lease_list as &$itme) {
                $itme['begin_time'] = dateDFormat($itme['begin_time']);
                $itme['end_time'] = dateDFormat($itme['end_time']);
                $itme['pay_time'] = dateFormat($itme['pay_time']);
            }
            $orderList['lease_list'] = $lease_list;
        }

        return $orderList;
    }

    /**
     * 划扣订单提前提醒列表(订单划扣日提前3天),可根据某个日期筛选
     * @param $request
     * @param array $where
     * @return array
     */
    public static function orderRemindList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus', '');
        $riskMobile = $request->input('riskMobile', '');
        $shopName = $request->input('shopName', '');
        $certName = $request->input('certName', '');
        $orderCreateTime = $request->input('orderCreateTime');
        $orderNo = $request->input('orderNo', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);

        if ($riskMobile) {
            $where[] = ['m.mobile', $riskMobile];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($certName) {
            $where[] = ['m.cert_name', 'like', '%' . $certName . '%'];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        $where[] = ['ol.which_period', '!=', 1];

        $orderList = Order::from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
            ->select(
                'o.id', 'o.status', 'o.trade_no','o.location', 'o.phone_brand', 'o.rent_total', 'o.month_total', 'o.amount', 'o.pay_type', 'o.foregift', 'o.foregift_deduct'
                , 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.sign_status', 'o.guarantee_status', 'o.pact_url', 'o.is_skip', 'o.order_from'
                , 'o.prov', 'o.city', 'o.area', 'o.begin_time', 'o.end_time', 'o.create_time', 'o.rights_auth_no',  'o.is_abnormal'
                , 'o.is_renewal', 'o.parent_order_no', 'o.emergency_contact', 'o.seller_id'
                , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type'
                , 'm.mobile', 'm.cert_name', 'm.cert_no', 'm.idcard_front', 'm.idcard_back', 'm.gender'
                , 's.shopname', 'o.sale_user_id','o.scene',
                'ol.id as ol_id', 'ol.begin_time as ol_begin_time', 'ol.end_time as ol_end_time', 'ol.status as ol_status'
            );
        //根据某个时间点,查询3天后要扣款的订单,(到第四天的凌晨)
//        $orderCreateTime=strtotime('-10 day');

        if ($orderStatus && in_array($orderStatus, [9, 10, 11, 12, 13, 14, 15, 20, 30, 31, 32, 33, 34, 38, 39, 40, 41, 42, 43, 44])) {
            $where[] = ['o.status', $orderStatus];
        } else {
            $orderList->wherein('o.status', [9, 10, 11, 12, 13, 14, 15, 20, 30, 31, 32, 33, 34, 38, 39, 40, 41, 42, 43, 44]);
        }
//        $where[]=[DB::Raw('ol.status in(0,4)')];
//        $where[] = ['ol.begin_time','>=',];
        $orderList->where($where);
//        $wherein = [0, 4];
//        $orderList->wherein('ol.status', $wherein);


//        $end_time = $orderCreateTime + 60 * 60 * 24 * 1-1;
//        $wherebetween = [$orderCreateTime, $end_time];
//        $orderList->wherebetween('ol.begin_time', $wherebetween);
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $wherebetween = [strtotime($orderCreateTime[0]), strtotime($orderCreateTime[1])];
            $orderList->wherebetween('ol.begin_time', $wherebetween);
        } else {
            $wherebetween = [strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))];
            $orderList->wherebetween('ol.begin_time', $wherebetween);
        }

        $orderList->orderBy('ol.begin_time', 'asc');
        $orderList->orderBy('o.id', 'desc');
        $list = obToArray($orderList->paginate($pageSize));
        if (isset($list['data'])) {
            foreach ($list['data'] as $k => $value) {
                //订单状态
                $list['data'][$k]['scene_dec'] = AlipayScene::where('scene',$value['scene'])->value('dec');
                $list['data'][$k]['address'] = AddressRemoveRepeat($value['prov'], $value['city'], $value['area'], $value['address']);
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$value['status']];
                $list['data'][$k]['create_time'] = dateFormat($value['create_time']);
                $list['data'][$k]['pact_type'] = GoodsService::getGoodsPactName($value['pact_type']);
                //订单来源
                $source = Source::where(['source_code' => $value['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                if ($value['order_from'] == 'saleOnline' && $value['openId']) {
                    $source = $source . '-微信';
                }
                if ($value['order_from'] == 'saleOnline' && empty($value['openId'])) {
                    $source = $source . '-支付宝';
                }
                if ($value['contract_no']) {
                    $source = $source . '-W';
                }
                $channel_name = SaleUser::where('sale_user_id', $value['sale_user_id'])->value('channel_name');
                if ($channel_name) {
                    $source = $source . '-' . $channel_name;
                }
                if ($value['sale_user_id']) {
                    $source = $source . '-' . $value['sale_user_id'];
                }
                $shopRate = OrderRate::where(['order_id' => $value['id']])->value('shop_rate');
                $shopRate = !empty($shopRate) ? "(" . $shopRate . "%)" : '';
                $list['data'][$k]['source'] = $source . $shopRate;
                //风控信息
                $list['data'][$k]['risk'] = '';
                if ($value['is_skip'] == Order::RISK_SKIP_NOT) {
                    $risk = RiskCredit::getRiskCredit($value['id']);
                    if ($risk) {
                        $list['data'][$k]['risk'] = '验证分' . $risk['verification_score'] . ';欺诈分' . $risk['cheat_score'] . ';' . $risk['final_decision'];
                    }
                }
                //实名认证
                $authenticLog = AuthenticLog::where(['order_id' => $value['id'], 'status' => AuthenticLog::AUTHENTIC_STATUS_PASS])->select('status')->first();
                $list['data'][$k]['authentic'] = [
                    'age' => getAgeByID($value['cert_no']),
                    'sex' => get_sex($value['cert_no']),
                    'status' => $authenticLog ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                ];
                //物流信息
                $list['data'][$k]['logistic'] = [];
                if ($value['status'] >= OrderService::ORDER_STATUS_DELIVER_SUCCESS) {
                    $logistics = Logistics::where(['order_id' => $value['id'], 'type' => Logistics::EXPRESS_TYPE_SEND])->select('logistics_name', 'logistics_no', 'delivery_type', 'status')->first();
                    $list['data'][$k]['logistic'] = $logistics ? obToArray($logistics) : [];
                }
                $log = OrderLease::getLeaseData($value['id'], $value['trade_no']);
                //租金 下期待付款
                $list['data'][$k]['lease'] = $log['count'];
                //流水记录
                $list['data'][$k]['leaseFlow'] = $log['lease_log'];
                //客服备注
                $list['data'][$k]['orderRemark'] = OrderRemark::getRemark($value['id']);
                //退款原因
                $list['data'][$k]['orderRefundReason'] = '';
                if (in_array($value['status'], OrderService::getOrderStatus(OrderService::ORDER_REFUND_STATUS))) {
                    $list['data'][$k]['orderRefundReason'] = OrderRefund::where(['order_id' => $value['id']])->value('refund_reason');
                }
            }
        }

        //对应状态统计
        $listCount = Order::from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select('o.status', DB::raw('count(*) as count'))
            ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
            ->where($where)
//            ->wherein('ol.status', $wherein)
            ->wherebetween('ol.begin_time', $wherebetween)
            ->groupBy(['o.status'])
            ->get();
        $listCount = obToArray($listCount);
        return ['count' => $listCount, 'list' => $list];
    }


    /**
     * 逾期订单
     * @param $request
     * @param array $where
     * @return array
     */
    public static function orderOverdueList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus', '');
        $riskMobile = $request->input('riskMobile', '');
        $shopName = $request->input('shopName', '');
        $certName = $request->input('certName', '');
        $orderCreateTime = $request->input('orderCreateTime');
        $orderNo = $request->input('orderNo', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $leaseBeginTime = $request->input('leaseBeginTime');

        if ($riskMobile) {
            $where[] = ['m.mobile', $riskMobile];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($certName) {
            $where[] = ['m.cert_name', 'like', '%' . $certName . '%'];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        $where[] = ['ol.which_period', '!=', 1];


        //根据某个时间点,查询3天后要扣款的订单,(到第四天的凌晨)
//        $orderCreateTime=strtotime('-10 day');


        if ($leaseBeginTime) {
            $leaseBeginTime = explode('~', $leaseBeginTime);
            $wherebetween = [strtotime($leaseBeginTime[0]), strtotime($leaseBeginTime[1])];


            $orderids = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->whereIn('o.status', [20, 30, 38, 39])
                ->wherebetween('ol.begin_time', $wherebetween)
                ->where('ol.status', '<>', 1)
                ->orderBy('ol.id', 'asc')
                ->groupBy('ol.order_id')
                ->select('ol.id', 'ol.order_id')->get();
            $orderids = obToArray($orderids);
            $order_ids = [];
            foreach ($orderids as $k => $v) {
                $status = OrderLease::where('id', '<', $v['id'])->where('order_id', $v['order_id'])->orderBy('id', 'desc')->select('status', 'order_id')->first();
                if ($status['status'] == 1) {
                    $order_ids[] = $status['order_id'];
                }
            }

            $orderList = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->whereIn('o.id', obToArray($order_ids))
                ->select(
                    'o.id', 'o.status', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.amount', 'o.pay_type', 'o.foregift', 'o.foregift_deduct'
                    , 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.sign_status', 'o.guarantee_status', 'o.pact_url', 'o.is_skip', 'o.order_from'
                    , 'o.prov', 'o.city', 'o.area', 'o.begin_time', 'o.end_time', 'o.create_time', 'o.rights_auth_no',  'o.is_abnormal'
                    , 'o.is_renewal', 'o.parent_order_no', 'o.emergency_contact', 'o.seller_id',  'o.sale_user_id'
                    , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type'
                    , 'm.mobile', 'm.cert_name', 'm.cert_no', 'm.idcard_front', 'm.idcard_back', 'm.gender'
                    , 's.shopname',
                );
        } else {
            $orderList = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->select(
                    'o.id', 'o.status', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.amount', 'o.pay_type', 'o.foregift', 'o.foregift_deduct'
                    , 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.sign_status', 'o.guarantee_status', 'o.pact_url', 'o.is_skip', 'o.order_from'
                    , 'o.prov', 'o.city', 'o.area', 'o.begin_time', 'o.end_time', 'o.create_time', 'o.rights_auth_no',  'o.is_abnormal'
                    , 'o.is_renewal', 'o.parent_order_no', 'o.emergency_contact', 'o.seller_id', 'o.guarantee_num'
                    , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type'
                    , 'm.mobile', 'm.cert_name', 'm.cert_no', 'm.idcard_front', 'm.idcard_back', 'm.gender'
                    , 's.shopname',
                    'ol.id as ol_id', 'ol.begin_time as ol_begin_time', 'ol.end_time as ol_end_time', 'ol.status as ol_status'
                );
            if ($orderStatus) {
                if ($orderStatus == 1) {
                    $wherebetween = [strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))];
                    $orderList->wherebetween('ol.begin_time', $wherebetween);
                    $where[] = ['ol.status', 0];
                } else if ($orderStatus == 2) {
                    $where[] = ['ol.status', 4];
                    $where[] = ['ol.overdue_days', 1];
                } else if ($orderStatus == 3) {
                    $where[] = ['ol.status', 4];
                    $where[] = ['ol.overdue_days', '>=', 2];
                    $where[] = ['ol.overdue_days', '<=', 7];
                } else if ($orderStatus == 4) {
                    $where[] = ['ol.status', 4];
                    $where[] = ['ol.overdue_days', '>=', 8];
                    $where[] = ['ol.overdue_days', '<=', 15];
                } else if ($orderStatus == 5) {
                    $where[] = ['ol.status', 4];
                    $where[] = ['ol.overdue_days', '>', 15];
                }
            }

            $orderList->wherein('o.status', [9, 10, 11, 12, 13, 14, 15, 20, 30, 31, 32, 33, 34, 38, 39, 40, 41, 42, 43, 44]);

            $orderList->where($where);

            if ($orderCreateTime) {
                $orderCreateTime = explode('~', $orderCreateTime);
                $wherebetween = [strtotime($orderCreateTime[0]), strtotime($orderCreateTime[1])];
                $orderList->wherebetween('ol.begin_time', $wherebetween);
            }
            $orderList->orderBy('ol.begin_time', 'asc');
        }


        $orderList->orderBy('o.id', 'desc');
        $list = obToArray($orderList->paginate($pageSize));

        if (isset($list['data'])) {
            foreach ($list['data'] as $k => $value) {
                //订单状态
                $list['data'][$k]['address'] = AddressRemoveRepeat($value['prov'], $value['city'], $value['area'], $value['address']);
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$value['status']];
                $list['data'][$k]['create_time'] = dateFormat($value['create_time']);
                $list['data'][$k]['pact_type'] = GoodsService::getGoodsPactName($value['pact_type']);
                $source = Source::where(['source_code' => $value['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                if ($value['order_from'] == 'saleOnline' && $value['openId']) {
                    $source = $source . '-微信';
                }
                if ($value['order_from'] == 'saleOnline' && empty($value['openId'])) {
                    $source = $source . '-支付宝';
                }
                if ($value['contract_no']) {
                    $source = $source . '-W';
                }
                $channel_name = SaleUser::where('sale_user_id', $value['sale_user_id'])->value('channel_name');
                if ($channel_name) {
                    $source = $source . '-' . $channel_name;
                }
                if ($value['sale_user_id']) {
                    $source = $source . '-' . $value['sale_user_id'];
                }
                //订单来源
                $shopRate = OrderRate::where(['order_id' => $value['id']])->value('shop_rate');
                $shopRate = !empty($shopRate) ? "(" . $shopRate . "%)" : '';
                $list['data'][$k]['source'] = $source . $shopRate;
                //风控信息
                $list['data'][$k]['risk'] = '';
                if ($value['is_skip'] == Order::RISK_SKIP_NOT) {
                    $risk = RiskCredit::getRiskCredit($value['id']);
                    if ($risk) {
                        $list['data'][$k]['risk'] = '验证分' . $risk['verification_score'] . ';欺诈分' . $risk['cheat_score'] . ';' . $risk['final_decision'];
                    }
                }
                //实名认证
                $authenticLog = AuthenticLog::where(['order_id' => $value['id'], 'status' => AuthenticLog::AUTHENTIC_STATUS_PASS])->select('status')->first();
                $list['data'][$k]['authentic'] = [
                    'age' => getAgeByID($value['cert_no']),
                    'sex' => get_sex($value['cert_no']),
                    'status' => $authenticLog ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                ];
                //物流信息
                $list['data'][$k]['logistic'] = [];
                if ($value['status'] >= OrderService::ORDER_STATUS_DELIVER_SUCCESS) {
                    $logistics = Logistics::where(['order_id' => $value['id'], 'type' => Logistics::EXPRESS_TYPE_SEND])->select('logistics_name', 'logistics_no', 'delivery_type', 'status')->first();
                    $list['data'][$k]['logistic'] = $logistics ? obToArray($logistics) : [];
                }
                $log = OrderLease::getLeaseData($value['id'], $value['trade_no']);
                //租金 下期待付款
                $list['data'][$k]['lease'] = $log['count'];
                //流水记录
                $list['data'][$k]['leaseFlow'] = $log['lease_log'];
                //客服备注
                $list['data'][$k]['orderRemark'] = OrderRemark::getRemark($value['id']);
                //退款原因
                $list['data'][$k]['orderRefundReason'] = '';
                if (in_array($value['status'], OrderService::getOrderStatus(OrderService::ORDER_REFUND_STATUS))) {
                    $list['data'][$k]['orderRefundReason'] = OrderRefund::where(['order_id' => $value['id']])->value('refund_reason');
                }
            }
        }

        //对应状态统计
        $listCount = Order::from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->select('o.status', DB::raw('count(*) as count'))
            ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
            ->where($where)
//            ->wherein('ol.status', $wherein)
//            ->wherebetween('ol.begin_time', $wherebetween)
            ->groupBy(['o.status'])
            ->get();
        $listCount = obToArray($listCount);
        return ['count' => $listCount, 'list' => $list];
    }

    /**
     * 财务订单列表
     * @param $request
     * @param array $where
     * @param string $shop
     * @return array|false|string
     */
    public static function financeOrderList($request, $where = [], $shop = '')
    {
        $orderStatus = $request->input('orderStatus');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $leaseTime = $request->input('leaseTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $leaseTerm = $request->input('leaseTerm', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['o.pay_type', '!=', Order::ORDER_PAY_TYPE_HUABEI];
        if ($orderStatus) {
            if ($orderStatus > OrderService::ORDER_STATUS_NOT_PAY) {
                $where[] = ['o.status', $orderStatus];
            } else {
                return ['list' => []];
            }
        } else {
            $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($leaseTerm) {
            $where[] = ['ol.which_period', $leaseTerm];
        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }
        if ($leaseTime) {
            $leaseTime = explode('~', $leaseTime);
            $where[] = ['ol.begin_time', '>=', strtotime($leaseTime[0])];
            $where[] = ['ol.begin_time', '<=', strtotime($leaseTime[1])];
        }
        if ($orderPayTime) {
            $orderPayTime = explode('~', $orderPayTime);
            $where[] = ['ol.pay_time', '>=', strtotime($orderPayTime[0])];
            $where[] = ['ol.pay_time', '<=', strtotime($orderPayTime[1])];
        }

        $list = Order::from('sp_order_2 as o')
            ->select(
                'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status', 'o.realname'
                , 'o.mobile', 'o.address', 'o.create_time', 'o.order_from', 'o.prov', 'o.city', 'o.area'
                , 'o.seller_id', 'o.uid', 'o.pay_type'
                , 'og.goods_title'
                , 's.shopname'
            )
            ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->where($where)
            ->orderBy('o.id', 'desc')
            ->groupBy('o.id')
            ->paginate($pageSize);
        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
//                $list['data'][$k]['shopname'] = ShopUser::where(['member_id'=>$item['seller_id']])->value('shopname');
                //订单状态
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                //订单来源
                $list['data'][$k]['source'] = Source::where(['source_code' => $item['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                $list['data'][$k]['real_auth'] = MemberOther::where(['id' => $item['uid']])->select('cert_no', 'cert_name')->first()->toArray();
                $lease = OrderLease::where(['order_id' => $item['order_id']])->select(
                    'id', 'which_period', 'rent', 'paid_rent', 'begin_time'
                    , 'end_time', 'status', 'pay_time', 'pay_type', 'settle_amount'
                    , 'settle_type', 'settle_time', 'reason', 'withhold_status', 'overdue_days'
                )->get();
                $lease = obToArray($lease);
                foreach ($lease as &$v) {
                    //代扣按钮 默认关闭
                    $v['is_withhold'] = OrderLease::LEASE_WITHHOLD_STATUS_OFF;
                    if (OrderLease::withholdLimit($item['status'], $v['withhold_status'], $v['begin_time'], $v['status'], $shop ? true : false)) {
                        $v['is_withhold'] = OrderLease::LEASE_WITHHOLD_STATUS_NO;
                    }
                    $v['withhold_num'] = OtherWithholdLog::where(['lease_id' => $v['id']])->count();
                    $v['begin_time'] = dateDFormat($v['begin_time']);
                    $v['end_time'] = dateDFormat($v['end_time']);
                    $v['pay_time'] = dateFormat($v['pay_time']);
                }
                $list['data'][$k]['lease'] = $lease;
            }
        }
        return ['list' => $list];
    }

    /**
     * 财务回款列表
     * @param $request
     * @param array $where
     * @param string $shop
     * @return array|false|string
     */
    public static function financeCollectionList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $receivingMobile = $request->input('receivingMobile', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $leaseTime = $request->input('leaseTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $leaseTerm = $request->input('leaseTerm', '');
        $refundTime = $request->input('refundTime', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['og.lease_set', OrderGoods::LEASE_SET_MONTH];
        if ($orderStatus) {
            if ($orderStatus > OrderService::ORDER_STATUS_NOT_PAY) {
                $where[] = ['o.status', $orderStatus];
            } else {
                return ['list' => []];
            }
        } else {
            $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($receivingMobile) {
            $where[] = ['o.mobile', $receivingMobile];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($leaseTerm) {
            $where[] = ['o.month_total', $leaseTerm];
        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }
        if ($leaseTime) {
            $leaseTime = explode('~', $leaseTime);
            $where[] = ['ol.begin_time', '>=', strtotime($leaseTime[0])];
            $where[] = ['ol.begin_time', '<=', strtotime($leaseTime[1])];
        }
        if ($orderPayTime) {
            $orderPayTime = explode('~', $orderPayTime);
            $where[] = ['ol.pay_time', '>=', strtotime($orderPayTime[0])];
            $where[] = ['ol.pay_time', '<=', strtotime($orderPayTime[1])];
        }
        if ($refundTime) {
            //退款类型
            $where[] = ['trans.trans_type', ShopTrans::ORDER_TRANS_TYPE_REFUND];
            $refundTime = explode('~', $refundTime);
            $where[] = ['trans.create_time', '>=', $refundTime[0]];
            $where[] = ['trans.create_time', '<=', $refundTime[1]];
        }

        $handel = Order::from('sp_order_2 as o');
        $handel->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id');
        $handel->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handel->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        if ($refundTime) {
            $handel->leftjoin('sp_shop_trans as trans', 'ol.id', 'trans.order_lease_id');
            $handel->select(
                'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
                , 'o.realname', 'o.mobile', 'o.create_time'
                , 'og.goods_title'
                , 's.shopname'
            );
        } else {
            $handel->select(
                'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
                , 'o.realname', 'o.mobile', 'o.create_time'
                , 'og.goods_title'
                , 's.shopname'
            );
        }

        $handel->where($where);
        $handel->orderBy('o.id', 'desc');
        $handel->groupBy('o.id');
        $list = $handel->paginate($pageSize);
        $list = obToArray($list);
        $dataInit = [];
        for ($i = 1; $i <= 12; $i++) {
            $dataInit[$i] = ['begin_time' => '', 'rent' => '', 'settle_time' => '', 'settle_amount' => ''];
        }
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                $list['data'][$k]['month_rent'] = $item['rent_total'] / $item['month_total'];
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
                $lease = OrderLease::where(['order_id' => $item['order_id']])->select(
                    'id', 'which_period', 'rent', 'paid_rent', 'begin_time'
                    , 'status', 'pay_time', 'settle_amount', 'settle_time'
                )->get();
                $lease = obToArray($lease);
                $total_payed = 0;
                $total_pay = 0;
                $data = $dataInit;
                foreach ($lease as $v) {
                    if (!in_array($item['status'], [OrderService::ORDER_STATUS_PART_REFUND, OrderService::ORDER_STATUS_REFUND_SUCCESS]) && $v['status'] == OrderLease::ORDER_LEASE_STATUS_PAID && isset($data[$v['which_period']])) {
                        $data[$v['which_period']]['begin_time'] = dateDFormat($v['begin_time']);
                        $data[$v['which_period']]['rent'] = $v['rent'];
                        if ($v['settle_time'] && $v['settle_amount']) {
                            $data[$v['which_period']]['settle_time'] = $v['settle_time'];
                            $data[$v['which_period']]['settle_amount'] = $v['settle_amount'];
                        }
                        $total_payed += $v['rent'];
                    }
                    if ($v['begin_time'] < time()) {
                        $total_pay += $v['rent'];
                    }

                }
                $list['data'][$k]['lease'] = $data;
                $owe_pay = $total_pay - $total_payed;
                $list['data'][$k]['total_pay'] = $total_pay;
                $list['data'][$k]['owe_pay'] = $owe_pay > 0 ? $owe_pay : '';
                if (in_array($item['status'], [OrderService::ORDER_STATUS_PART_REFUND, OrderService::ORDER_STATUS_REFUND_SUCCESS, OrderService::ORDER_STATUS_COMPLETED])) {
                    $list['data'][$k]['rent_total'] = '';//累计应收
                    $list['data'][$k]['total_pay'] = '';//累计应付
                    $list['data'][$k]['owe_pay'] = '';//欠收金额
                }
                if (in_array($item['status'], [OrderService::ORDER_STATUS_BUYOUT_PAY])) {
                    $list['data'][$k]['total_pay'] = $item['rent_total'];
                    $list['data'][$k]['owe_pay'] = '';
                }
            }
        }
        return ['list' => $list];
    }

    /**
     * 设备分期列表
     * @param $request
     * @param array $where
     * @param string $shop
     * @return array|false|string
     */
    public static function financeEquipmentList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['og.lease_set', OrderGoods::LEASE_SET_MONTH];
        if ($orderStatus) {
            if ($orderStatus > OrderService::ORDER_STATUS_NOT_PAY) {
                $where[] = ['o.status', $orderStatus];
            } else {
                return ['list' => []];
            }
        } else {
            $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }

        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }

        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }

        $handel = Order::from('sp_order_2 as o');
        $handel->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handel->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        $handel->select(
            'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
            , 'o.create_time', 'o.amount', 'o.begin_time', 'o.end_time'
            , 'og.goods_title'
            , 's.shopname'
        );
        $handel->where($where);
        $handel->orderBy('o.id', 'desc');
        $handel->groupBy('o.id');
        $list = $handel->paginate($pageSize);
        $list = obToArray($list);
        $beginDate = date('Y-m-01 00:00:00', time());
        $endDate = date('Y-m-d 23:59:59', strtotime("$beginDate +1 month -1 day"));
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
                $list['data'][$k]['begin_time'] = dateDFormat(strtotime($item['begin_time']));
                $list['data'][$k]['end_time'] = dateDFormat(strtotime($item['end_time']));
                $list['data'][$k]['status'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                //月租金/台
                $list['data'][$k]['month_rent'] = $item['rent_total'] / $item['month_total'] / $item['amount'];
                //租金/台
                $list['data'][$k]['company_rent'] = $item['rent_total'] / $item['amount'];

                $periods = 0; //当月应收期数
                $rent = 0; //当月应收金额
                $pay_money = 0;//当月实收金额
                $total_leasenum1 = 0;
                $total_paymoney2 = 0;
                $total_money1 = 0;
                $default_money = 0;
                $lease = OrderLease::where(['order_id' => $item['order_id']])->select('id', 'which_period', 'rent', 'status', 'paid_rent', 'begin_time')->get();
                $lease = obToArray($lease);
                foreach ($lease as $value) {
                    if ($value['begin_time'] >= strtotime($beginDate) && $value['begin_time'] <= strtotime($endDate)) {
                        $periods = 1;
                        $rent = $value['rent'];
                        if ($value['status'] != OrderLease::ORDER_LEASE_STATUS_NOPAY) {
                            $pay_money = $value['rent'];
                        }
                    }
                    if ($value['begin_time'] <= strtotime($endDate)) {
                        if ($value['status'] != OrderLease::ORDER_LEASE_STATUS_REFUNDED) {
                            $total_leasenum1++;
                            $total_money1 += $value['rent'];
                        }
                        if ($value['status'] == OrderLease::ORDER_LEASE_STATUS_PAID) {
                            $total_paymoney2 += $value['rent'];
                        }
                    }
                    if (time() >= strtotime($item['end_time']) && $value['status'] == OrderLease::ORDER_LEASE_STATUS_NOPAY) {
                        $default_money += $value['rent'];
                    }
                }

                $list['data'][$k]['periods'] = !empty($periods) ? $periods : '';
                $list['data'][$k]['rent'] = !empty($rent) ? $rent : '';
                $list['data'][$k]['pay_money'] = !empty($pay_money) ? $pay_money : '';
                $overdue_money = $rent - $pay_money;
                $list['data'][$k]['overdue_money'] = !empty($overdue_money) ? sprintf('%.2f', $overdue_money) : '';
                $total_leasenum = $total_leasenum1;
                $list['data'][$k]['total_leasenum'] = !empty($total_leasenum) ? $total_leasenum : '';
                $total_paymoney = $total_paymoney2;
                $list['data'][$k]['total_paymoney'] = !empty($total_paymoney) ? $total_paymoney : '';
                $total_money = $total_money1;
                $list['data'][$k]['total_money'] = !empty($total_money) ? $total_money : '';
                $total_overduemoney = $total_money - $total_paymoney;
                $list['data'][$k]['total_overduemoney'] = !empty($total_overduemoney) ? sprintf('%.2f', $total_overduemoney) : '';
                $receivables = $item['rent_total'] - $total_paymoney;
                $list['data'][$k]['receivables'] = sprintf('%.2f', $receivables);
                $list['data'][$k]['default_money'] = $default_money ? $default_money : '';
                //退款成功、买断付款、交易完成
                if (in_array($item['status'], [
                    OrderService::ORDER_STATUS_PART_REFUND,
                    OrderService::ORDER_STATUS_REFUND_SUCCESS,
                    OrderService::ORDER_STATUS_BUYOUT_PAY,
                    OrderService::ORDER_STATUS_COMPLETED,
                ])) {
                    $list['data'][$k]['periods'] = ''; //当月应收期数
                    $list['data'][$k]['rent'] = ''; //当月应收金额
                    $list['data'][$k]['pay_money'] = ''; //当月实收金额
                    $list['data'][$k]['overdue_money'] = ''; //当月逾期金额=当月应收金额-当月实收金额
                    $list['data'][$k]['total_leasenum'] = ''; //累计应收期数
                    $list['data'][$k]['total_money'] = ''; //累计应收金额
                    $list['data'][$k]['total_paymoney'] = ''; //累计实收金额
                    $list['data'][$k]['total_overduemoney'] = ''; //累计逾期金额
                    $list['data'][$k]['receivables'] = ''; //应收账款=总租金-累计实收金额
                    $list['data'][$k]['default_money'] = ''; //违约金额
                }
            }
        }
        return ['list' => $list];
    }

    /**
     * 财务账单列表
     * @param $request
     * @param array $where
     * @return array|false|string
     */
    public static function financeLeaseList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $receivingMobile = $request->input('receivingMobile', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $leaseTime = $request->input('leaseTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $leaseTerm = $request->input('leaseTerm', '');
        $refundTime = $request->input('refundTime', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['o.pay_type', '!=', Order::ORDER_PAY_TYPE_HUABEI];
        if ($orderStatus) {
            if ($orderStatus > OrderService::ORDER_STATUS_NOT_PAY) {
                $where[] = ['o.status', $orderStatus];
            } else {
                return ['list' => []];
            }
        } else {
            $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        }
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($receivingMobile) {
            $where[] = ['o.mobile', 'like', '%' . $receivingMobile . '%'];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($leaseTerm) {
            $where[] = ['ol.which_period', $leaseTerm];
        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }
        if ($leaseTime) {
            $leaseTime = explode('~', $leaseTime);
            $where[] = ['ol.begin_time', '>=', strtotime($leaseTime[0])];
            $where[] = ['ol.begin_time', '<=', strtotime($leaseTime[1])];
        }
        if ($orderPayTime) {
            $orderPayTime = explode('~', $orderPayTime);
            $where[] = ['ol.pay_time', '>=', strtotime($orderPayTime[0])];
            $where[] = ['ol.pay_time', '<=', strtotime($orderPayTime[1])];
        }
        if ($refundTime) {
            $refundTime = explode('~', $refundTime);
            $where[] = ['ol.refund_time', '>=', $refundTime[0]];
            $where[] = ['ol.refund_time', '<=', $refundTime[1]];
        }

        $handel = Order::from('sp_order_2 as o');
        $handel->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id');
        $handel->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handel->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        $handel->select(
            'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
            , 'o.prov', 'o.city', 'o.area'
            , 'o.realname', 'o.mobile', 'o.address'
            , 'o.create_time', 'o.order_from', 'o.sync_status'
            , 'o.begin_time as order_begin_time', 'o.end_time as order_end_time'
            , 'og.goods_title'
            , 's.shopname'
            , 'ol.id as lease_id', 'ol.which_period', 'ol.rent', 'ol.paid_rent', 'ol.begin_time'
            , 'ol.end_time', 'ol.status as lease_status', 'ol.pay_time', 'ol.pay_type', 'ol.settle_amount'
            , 'ol.settle_type', 'ol.settle_time', 'ol.reason', 'ol.withhold_status', 'ol.overdue_days', 'ol.refund_time as trans_create_time'
        );
        $handel->where($where);
        $handel->orderBy('o.id', 'desc');
        $list = $handel->paginate($pageSize);
        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                if ($item['which_period'] > $item['month_total']) {
                    $list['data'][$k]['month_total'] = $item['which_period'];
                }
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
                //客服备注
                $list['data'][$k]['orderRemark'] = OrderRemark::getRemark($item['order_id']);
                //订单状态
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                //订单来源
                $source = Source::where(['source_code' => $item['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                $list['data'][$k]['source'] = $source;
                $list['data'][$k]['begin_time'] = dateDFormat($item['begin_time']);
                $list['data'][$k]['end_time'] = dateDFormat($item['end_time']);
                $list['data'][$k]['pay_time'] = dateFormat($item['pay_time']);
                $list['data'][$k]['withhold_num'] = OtherWithholdLog::where(['lease_id' => $item['lease_id']])->count();
                if ($item['lease_status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED) {
                    if ($item['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES) {
                        $list['data'][$k]['trans_amount'] = ShopTrans::where(['trans_type' => ShopTrans::ORDER_TRANS_TYPE_REFUND, 'order_lease_id' => $item['lease_id']])->value('amount');
                    } else {
                        $list['data'][$k]['trans_amount'] = $item['paid_rent'];
                    }
                } else {
                    $list['data'][$k]['trans_create_time'] = '';
                    $list['data'][$k]['trans_amount'] = '';
                }
            }
        }
        return ['list' => $list];
    }

    /**
     * 财务逾期列表
     * @param $request
     * @param array $where
     * @return array
     */
    public static function financeOverdueList($request, $where = [])
    {
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $receivingMobile = $request->input('receivingMobile', '');
        $shopName = $request->input('shopName', '');
        $leaseTime = $request->input('leaseTime', '');
        $overdueDay = $request->input('overdueDay', '');
        $sendStatus = $request->input('sendStatus', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['ol.status', OrderLease::ORDER_LEASE_STATUS_OVERDUE];
        $where[] = ['o.pay_type', '!=', Order::ORDER_PAY_TYPE_HUABEI];
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['o.realname', 'like', '%' . $receivingName . '%'];
        }
        if ($receivingMobile) {
            $where[] = ['o.mobile', 'like', '%' . $receivingMobile . '%'];
        }
        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($sendStatus) {
            $where[] = ['ol.msg_status', $sendStatus];
        }
        if ($overdueDay) {
            $overdueDay = explode('~', $overdueDay);
            $where[] = ['ol.overdue_days', '>=', $overdueDay[0]];
            $where[] = ['ol.overdue_days', '<=', $overdueDay[1]];
        }
        if ($leaseTime) {
            $leaseTime = explode('~', $leaseTime);
            $where[] = ['ol.begin_time', '>=', strtotime($leaseTime[0])];
            $where[] = ['ol.begin_time', '<=', strtotime($leaseTime[1])];
        }

        $handel = Order::from('sp_order_2 as o');
        $handel->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id');
        $handel->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handel->leftjoin('sp_member_2 as m', 'm.id', 'o.uid');
        $handel->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        $handel->select(
            'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
            , 'o.prov', 'o.city', 'o.area'
            , 'o.realname', 'o.mobile', 'o.address'
            , 'o.create_time'
            , 'o.begin_time as order_begin_time', 'o.end_time as order_end_time'
            , 'og.goods_title'
            , 's.shopname', 'm.cert_name'
            , 'ol.id as lease_id', 'ol.which_period', 'ol.rent', 'ol.paid_rent', 'ol.begin_time'
            , 'ol.end_time', 'ol.status as lease_status', 'ol.pay_time', 'ol.pay_type', 'ol.withhold_status', 'ol.overdue_days', 'ol.overdue_amount'
            , 'ol.msg_status as send_status'
        );
        $handel->where($where);
        $handel->orderBy('o.id', 'desc');
        $list = $handel->paginate($pageSize);
        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                //订单状态
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
                $list['data'][$k]['begin_time'] = dateDFormat($item['begin_time']);
                $list['data'][$k]['end_time'] = dateDFormat($item['end_time']);
                $list['data'][$k]['pay_time'] = dateFormat($item['pay_time']);
                $list['data'][$k]['withhold_num'] = OtherWithholdLog::where(['lease_id' => $item['lease_id']])->count();
                $list['data'][$k]['sms_num'] = 0;
                if ($item['send_status'] == OrderLease::ORDER_LEASE_OVERDUE_SEND_YES) {
                    $list['data'][$k]['sms_num'] = SmsRecord::where(['template_id' => SmsTemplate::SMS_TEMPLATE_ORDER_COLLECTION, 'lease_id' => $item['lease_id']])->count('id');
                }
            }
        }

        $handelCount = Order::from('sp_order_2 as o');
        $handelCount->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id');
        $handelCount->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handelCount->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        $handelCount->where($where);
        $overdueCount = $overdueAmount = $handelCount;
        $overdue['overdueCount'] = $overdueCount->count();
        $overdue['overdueAmount'] = $overdueAmount->sum('ol.overdue_amount');
        return ['count' => $overdue, 'list' => $list];
    }

    /**
     * 财务对账流水
     * @param $request
     * @param array $where
     * @return array
     */
    public static function reconciliationFlow($request, $where = [], $shop = '')
    {
        $orderNo = $request->input('orderNo', '');
        $shopName = $request->input('shopName', '');
        $moneyFlow = $request->input('moneyFlow', '');
        $flowType = $request->input('flowType', '');
        $createTime = $request->input('createTime', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $member_id = '';
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($shopName) {
            $member_id = ShopUser::where([['shopname', '=', $shopName]])->value('member_id');
            $where[] = ['t.member_id', $member_id];
        }
        if ($moneyFlow) {
            if ($moneyFlow == 1) {
                $where[] = ['t.amount', '>', 0];
            } else {
                $where[] = ['t.amount', '<=', 0];
            }
        }
        if ($flowType) {
            $where[] = ['t.trans_type', $flowType];
        }
        $orderIds = [];
        if ($createTime) {
            $createTime = explode('~', $createTime);
            $where[] = ['t.create_time', '>=', $createTime[0]];
            $where[] = ['t.create_time', '<=', $createTime[1]];
            $orderIds = ShopTrans::from('sp_shop_trans as t')
                ->where($where)
                ->distinct($where)
                ->pluck('order_id');
        }

        $list = ShopTrans::from('sp_shop_trans as t')
            ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
            ->leftjoin('sp_member_2 as u', 'u.id', 't.user_id')
            ->leftjoin('sp_order_lease_2 as ol', 't.order_lease_id', 'ol.id')
            ->select(
                'o.id as order_id', 'o.trade_no', 'o.month_total', 'ol.which_period', 'ol.paid_rent', 'u.cert_name', 'o.seller_id', 'o.sync_status'
                , 't.id as trans_id', 't.amount', 't.before_balance', 't.after_balance', 't.service_fee', 't.trans_type', 't.create_time', 't.remarks', 't.member_id'
            )
            ->where($where)
            ->orderBy('t.id', 'desc')
            ->paginate($pageSize);


        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                $list['data'][$k]['shop_mobile'] = NewAdmin::where(['user_id' => $item['member_id']])->value('mobile');
                $shopName = ShopUser::where(['member_id' => $item['member_id']])->value('shopname');
                $list['data'][$k]['shopname'] = $shopName;
                $list['data'][$k]['trans_type_name'] = ShopTrans::ORDER_TRANS_TYPE_LIST[$item['trans_type']];
            }
        }
        $where1 = [];
        if ($member_id) {
            $where1 = ['member_id' => $member_id];
        }
        if ($shop) {
            $where1 = ['member_id' => $shop];
            $where2 = ['o.seller_id' => $shop];
        }

        $totalAmount['time_amount'] = ShopTrans::from('sp_shop_trans as t')
            ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
            ->select(
                't.id as trans_id', 't.amount', 't.before_balance', 't.after_balance', 't.service_fee', 't.trans_type', 't.create_time', 't.remarks', 't.member_id'
            )
            ->where($where)
            ->sum('t.amount');

        $totalAmount['service_fee'] = ShopTrans::from('sp_shop_trans as t')
            ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
            ->where($where)
            ->sum('service_fee');
        $totalAmount['withdrawal'] = ShopTrans::from('sp_shop_trans as t')
            ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
            ->where($where)
            ->whereIn('t.trans_type', [ShopTrans::ORDER_TRANS_TYPE_WITHDRAWAL])
            ->sum('t.amount');
        $totalAmount['withdrawal'] = abs($totalAmount['withdrawal']);
        $totalAmount['charge'] = ShopTrans::from('sp_shop_trans as t')
            ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
            ->where($where)
            ->whereIn('t.trans_type', [ShopTrans::ORDER_TRANS_TYPE_CHARGE])
            ->sum('t.amount');

        if ($member_id) {
            $where2 = ['o.seller_id' => $member_id];
        }

        if ($orderIds) {

            $totalAmount['rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->where('ol.alipay_trade_no', '<>', '线下已支付')
                ->where($where2)
                ->whereIn('o.id', $orderIds)
                ->whereIn('o.status', OrderService::getOrderStatus(OrderService::ORDER_SETTLE_CONFIRM_STATUS))
                ->select('ol.rent')
                ->sum('ol.rent');

            $totalAmount['amount'] = ShopTrans::from('sp_shop_trans as t')
                ->leftjoin('sp_order_2 as o', 'o.id', 't.order_id')
                ->select(
                    't.id as trans_id', 't.amount', 't.before_balance', 't.after_balance', 't.service_fee', 't.trans_type', 't.create_time', 't.remarks', 't.member_id'
                )
                ->where($where)
                ->sum('t.amount');

            $totalAmount['overdue_rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->where($where2)
                ->whereIn('o.id', $orderIds)
                ->where('o.status', 39)
                ->where('ol.status', 4)
                ->select('ol.rent')
                ->sum('ol.rent') ;

            //采购金额（元）
            $totalAmount['purchase_amount'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->where($where2)
                ->whereIn('o.id', $orderIds)
                ->whereIn('o.status', OrderService::getOrderStatus(OrderService::ORDER_SETTLE_STATUS))
                ->sum('og.acquisition_price');

        } else {
            $totalAmount['amount'] = ShopUser::where($where1)->sum('shop_balance');//供应商总额
            //总租金（元）
            $totalAmount['rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->where('ol.alipay_trade_no', '<>', '线下已支付')
                ->where($where2)
                ->whereIn('o.status', OrderService::getOrderStatus(OrderService::ORDER_SETTLE_CONFIRM_STATUS))
                ->select('ol.rent')
                ->sum('ol.rent');


                $totalAmount['overdue_rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                        ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                        ->where($where2)
                        ->where('o.status', 39)
                        ->where('ol.status', 4)
                        ->select('ol.rent')
                        ->sum('ol.rent') ;

                //采购金额（元）
                $totalAmount['purchase_amount'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->where($where2)
                    ->whereIn('o.status', OrderService::getOrderStatus(OrderService::ORDER_SETTLE_STATUS))
                    ->sum('og.acquisition_price');
        }


        return ['count' => $totalAmount, 'list' => $list];
    }

    /**
     * 花呗财务账单列表
     * @param $request
     * @param array $where
     * @return array|false|string
     */
    public static function financeHuaBeiList($request, $where = [])
    {
        $orderStatus = $request->input('orderStatus');
        $orderNo = $request->input('orderNo', '');
        $goodsName = $request->input('goodsName', '');
        $receivingName = $request->input('receivingName', '');
        $shopName = $request->input('shopName', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $orderPayTime = $request->input('orderPayTime', '');
        $leaseTerm = $request->input('leaseTerm', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $where[] = ['o.pay_type', Order::ORDER_PAY_TYPE_HUABEI];
        if ($orderStatus) {
            if ($orderStatus > OrderService::ORDER_STATUS_NOT_PAY) {
                $where[] = ['o.status', $orderStatus];
            } else {
                return ['list' => []];
            }
        } else {
            $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        }

        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($goodsName) {
            $where[] = ['og.goods_title', 'like', '%' . $goodsName . '%'];
        }
        if ($receivingName) {
            $where[] = ['au.cert_name', 'like', '%' . $receivingName . '%'];
        }

        if ($shopName) {
            $where[] = ['s.shopname', 'like', '%' . $shopName . '%'];
        }
        if ($leaseTerm) {
            $where[] = ['o.month_total', $leaseTerm];
        }
        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])];
        }

        if ($orderPayTime) {
            $orderPayTime = explode('~', $orderPayTime);
            $where[] = ['o.pay_time', '>=', strtotime($orderPayTime[0])];
            $where[] = ['o.pay_time', '<=', strtotime($orderPayTime[1])];
        }

        $handel = Order::from('sp_order_2 as o');
        $handel->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id');
        $handel->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id');
        $handel->leftjoin('sp_other_authentic_log as au', 'o.id', 'au.order_id');
        $handel->select(
            'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.status'
            , 'o.prov', 'o.city', 'o.area'
            , 'o.realname', 'o.mobile', 'o.address'
            , 'o.create_time', 'o.order_from', 'o.pay_time', 'o.alipay_trade_no', 'o.settlement_status', 'o.payment'
            , 'o.begin_time', 'o.end_time', 'o.settle_refuse_reason'
            , 'og.goods_title'
            , 's.shopname'
            , 'au.cert_no', 'au.cert_name'
        );
        $handel->where($where);
        $handel->orderBy('o.id', 'desc');
        $list = $handel->paginate($pageSize);
        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {
                $list['data'][$k]['create_time'] = dateFormat($item['create_time']);
                $list['data'][$k]['begin_time'] = dateDFormat(strtotime($item['begin_time']));
                $list['data'][$k]['end_time'] = dateDFormat(strtotime($item['end_time']));
                //订单状态
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                //订单来源
                $list['data'][$k]['source'] = Source::where(['source_code' => $item['order_from'], 'status' => Source::SOURCE_STATUS_ENABLE])->value('source_name');
                $list['data'][$k]['pay_time'] = dateFormat($item['pay_time']);
                $list['data'][$k]['settlement_create_time'] = '';
                $list['data'][$k]['settlement_amount'] = '';
                if ($item['settlement_status'] == Order::ORDER_HUABEI_SETTLE_STATUS_YES) {
                    $trans = ShopTrans::where(['order_id' => $item['order_id'], 'trans_type' => ShopTrans::ORDER_TRANS_TYPE_SETTLE])->select('amount', 'create_time')->first();
                    $trans = obToArray($trans);
                    $list['data'][$k]['settlement_create_time'] = isset($trans['create_time']) ? $trans['create_time'] : '';
                    $list['data'][$k]['settlement_amount'] = isset($trans['amount']) ? $trans['amount'] : '';
                }
                $list['data'][$k]['settlement_status'] = Order::ORDER_HUABEI_SETTLE_STATUS_LIST[$item['settlement_status']];
            }
        }
        return ['list' => $list];
    }

    //融资报单列表
    protected function GetReportBillList($pageSize, $where)
    {
        $select = array('o.id', 'o.trade_no', 'o.create_time', 'og.goods_title', 'og.setmeal_title', 'o.amount', 'o.month_total', 'o.rent_total',
            'o.realname', 'o.mobile', 'o.prov', 'o.city', 'o.area', 'o.address', 'o.status', 'o.sync_status', 'su.shopname');
        $data = $this
            ->from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', 'o.seller_id')
            ->select($select)
            ->where($where)
            ->orderBy('o.id', 'desc')
            ->paginate($pageSize);
        $data = $data ? $data->toArray() : [];
        return $data;
    }

    //融资报单导出数据
    protected function GetReportBillData($where)
    {
        $select = array('o.id', 'o.trade_no', 'o.create_time', 'og.goods_title', 'og.setmeal_title', 'o.amount', 'o.month_total', 'o.rent_total',
            'o.realname', 'o.mobile', 'o.prov', 'o.city', 'o.area', 'o.address', 'o.status', 'o.sync_status', 'su.shopname');
        $data = $this
            ->from('sp_order_2 as o')
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', 'o.seller_id')
            ->select($select)
            ->where($where)
            ->orderBy('o.id', 'desc')
            ->get();
        $data = $data ? $data->toArray() : [];
        return $data;
    }


    /**
     * 订单完结
     */
    protected function orderFinish($orderId, $member_id = '', $is_shop = false)
    {
        if ($is_shop) {
            $where[] = ['seller_id', $member_id];
        }
        $where[] = ['id', $orderId];
        $where[] = ['pay_type', self::ORDER_PAY_TYPE_ANTCHAIN];
        $order = $this->where($where)->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_FINISH_OPERATION_STATUS))
            ->select('id', 'mini_id', 'trade_no', 'sign_no', 'pay_type', 'status', 'alipay_trade_no', 'rights_auth_no', 'flow_id')->first();
        $order = obToArray($order);
        // dd($order);
        if (!empty($order)) {
            if ($order['sign_no']) {
                AntchainAtoService::cancelWithholdPlan($order['trade_no']);
                AntchainAtoService::closeOrder($order['trade_no']);
                AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "AGREE", null, 0, null);
            }
            if ($order['pay_type'] == OrderLease::LEASE_PAY_TYPE_ANTCHAIN) {
                $this->where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_COMPLETED]);
                $thaw_query = AntchainService::paytradeCancel($order['flow_id']);
                return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '操作成功', 'data' => []];
            }

            if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status']) {//解冻预授权，作废合同
                $miniId = $order['mini_id'];

                $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                $alipay_data['authNo'] = $order['rights_auth_no'];
                $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
                if ($prequery['status']) {
                    $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                    if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                        $thaw_data['amount'] = $rest_amount;
                        $thaw_data['authNo'] = $order['rights_auth_no'];
                        $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                        if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                            //查找扣款失败未履约的订单
                            $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                                ->groupBy('out_trade_no')
                                ->get();
                            foreach ($log as $value) {
                                $orderData = [
                                    'orderId' => $value['order_no'],
                                    'outTradeNo' => $value['out_trade_no'],
                                    'tradeNo' => $value['trade_no'],
                                    'status' => 'CLOSED',
                                ];
                                AlipayService::orderInfo($miniId, $orderData);
                            }
                        } else {
                            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '授权资金解冻失败，请联系平台客服解决', 'data' => []];
                        }
                    }
                } else {
                    return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未查到授权资金解冻，请联系平台客服解决', 'data' => []];
                }
            }

        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单不存在或者订单状态不允许该操作', 'data' => []];
        }
    }

    /**
     * 编辑订单数据-供应商
     */
    protected function editOrderData($request, $users = [])
    {
        $orderId = $request['orderId'];

        $seller_id = $request['seller_id']; // 新商家member_id

        //修改商家
        $data = [];
        $data['seller_id'] = $seller_id;


        $this->where('id', $orderId)->update($data);
//        DB::beginTransaction();
//        $shopuser = ShopUser::where('member_id',$seller_id)->select('account', 'account_type')->first();
//        $shopuser = obToArray($shopuser);
//        $rate_res=OrderRate::updateOrderRate($orderId,$order['goods_id'],$order['order_from'],$order['pay_type'],self::RISK_SKIP_YES,$shopuser['account'],$seller_id);
//        if($rate_res&&$res){
//            DB::commit();
//        }else{
//            DB::rollBack();
//        }

    }

    /**
     * 下载协议word
     */
    protected function downloadWord($orderId)
    {
        //1.创建模板对象

        $order = Order::from('sp_order_2 as o')
            ->leftjoin('sp_member_2 as u', 'o.uid', 'u.id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
            ->select("u.cert_name", "u.mobile", "u.cert_no",'g.new_grade', "o.trade_no", "o.amount", "og.goods_title", "og.setmeal_title", "og.goods_title")
            ->where("o.id", $orderId)
            ->first();

        $order = obToArray($order);

        $file = './export/template_express.docx';

        $document = new TemplateProcessor($file);

        $new_grade=GoodsService::getGoodsNewGrade($order['new_grade']);
        //2.插入数据
        //插入文字
        $document->setValue('goods_name', '('.$new_grade.')'.$order['goods_title']);
        $document->setValue('goods_no', $order['trade_no']);
        $document->setValue('goods_num', $order['amount']);
        $document->setValue('goods_meal', $order['setmeal_title']);
        $document->setValue('name', $order['cert_name']);

        $mobile = substr_replace($order['mobile'], '****', 3, 4);

        $document->setValue('mobile', $mobile);

        $cert_no = $order['cert_no'];

        $cert_no_start = substr($cert_no, 0, 6);

        $cert_no_end = substr($cert_no, 12);

        $cert_no_2 = $cert_no_start . '******' . $cert_no_end;

        $document->setValue('cert_no', $cert_no_2);

        //3.保存文件
        $fileName = $order['cert_name'] . 'orderID' . $orderId . '.docx';

        // $file = './export/' . $fileName;

        $file = public_path('/export/') . $fileName;

        $document->saveAs($file);

        chmod($file, 0777);

        return $file;
    }

    /**
     * 编辑订单数据-总租金
     */
    protected function editLeaseRents($request)
    {
        $orderId = $request['orderId'];

        $order = $this->where("id",$orderId)->select('begin_time')->first();
        $order = obToArray($order);

        if(isset($request['down_payment'])&&$request['down_payment']>0) {
            $pact_month_total=$request['month_total']-1;
        }else{
            $pact_month_total=$request['month_total'];
        }
        //期数总租金
        if($request['pact_type'] == OrderGoods::PACT_TYPE_RETURN_OUT){ //设置租完即送
            $rent=bcdiv($request['setmeal_foregift']-$request['down_payment'],$pact_month_total,2);
        }else{
            $rent = $request['rent'];
        }

        if($request['is_rent_choose'] == '1'){
            //首月1元
            $rent_total = ($request['month_total']-1)*$rent+1;

        }else if($request['is_rent_choose'] == '2'){
            //首月五折
            $rent_total = ($request['month_total']-1)*$rent+$rent*0.5;
        }else{
            $rent_total = bcmul($pact_month_total,$rent,2);
        }


        $data =[];

        //租期结束时间
        $days = $request['month_total']=='12'?'365':$request['month_total']*30;

        $data['end_time'] = date('Y-m-d H:i:s',strtotime($order['begin_time'])+$days*24*3600);

        $data['month_total'] = $request['month_total'];
        if(isset($request['down_payment'])&&$request['down_payment']>0){
            $rent_total= $rent_total+$request['down_payment'];
        }
        $data['rent_total'] = $rent_total;


        //碎屏险
        $data['is_insurance_choose'] = $request['is_insurance_choose'];
        $data['is_insurance_choose_custom'] = $request['is_insurance_choose_custom'];
        $data['is_rent_choose'] = $request['is_rent_choose'];
        $data['prepayment_total'] = $request['prepayment_total']??0;
        $res1 = $this->where("id",$orderId)->update($data);


        //修改买断款和市场价

        $order_data = [];

        $order_data['setmeal_foregift'] = $request['setmeal_foregift'];

        $order_data['setmeal_price'] = $request['setmeal_foregift'] - $rent_total;

        $order_data['lease_price'] = $rent;

        $order_data['lease_time'] = $days;

        $order_data['down_payment'] = $request['down_payment'];

        if(isset($request['lease_day'])&&$request['lease_day']>0){
            $order_data['lease_day'] = $request['lease_day'];
            $order_data['lease_set'] = GoodsService::GOODS_RENT_TYPE_MANAGER_CUSTOM;
        }else{
            $order_data['lease_set'] = GoodsService::GOODS_RENT_TYPE_DAY;
            $order_data['lease_day'] = 0;
        }

        $res = OrderGoods::where('order_id',$orderId)->update($order_data);

        if($res1 || $res){
            return true;
        }
    }

    /**
     * 分销商订单列表
     * @param $request
     * @param $sale_user_id
     * @param array $where
     * @return array|false|string
     */
    public static function saleOrderList($request, $sale_user_id, $where = [])
    {
        $orderNo = $request->input('trade_no', ''); //订单编号
        $cert_name = $request->input('cert_name', ''); //下单姓名
        $goods_name = $request->input('goods_name', ''); //商品名称
        $sale_name = $request->input('sale_name', ''); //推广员名称
        $name = $request->input('name', ''); //用户名称
        $phone = $request->input('phone', ''); //手机号码

        $begin_time = $request->input('begin_time', ''); //下单时间
        $order_status = $request->input('order_status', ''); //订单状态
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);

        $sale_user = SaleUser::where('parent_user_id', $sale_user_id)->select('sale_user_id')->get();
        $sale_user = obToArray($sale_user);
        $sale_users = array_column($sale_user, 'sale_user_id');
        $sale_users[] = $sale_user_id;
        // dd($sale_users);
        // $where[] = ['o.sale_user_id',$sale_user_id];
        if ($orderNo) {
            $where[] = ['o.trade_no', 'like', '%' . $orderNo . '%'];
        }
        if ($phone) {
            $where[] = ['m.mobile', 'like', '%' . $phone . '%'];
        }
        if ($name) {
            $where[] = ['m.cert_name', $name];
        }
        if ($goods_name) {
            $where[] = ['og.goods_name', 'like', '%' . $goods_name . '%'];
        }
        if ($sale_name) {
            $where[] = ['u.people', $sale_name];
        }
        if ($order_status) {
            $where[] = ['o.status', $order_status];
        }
        if ($begin_time) {
            $begin_time = explode('~', $begin_time);
            $where[] = ['o.create_time', '>=', strtotime($begin_time[0])];
            $where[] = ['o.create_time', '<=', strtotime($begin_time[1])];
        }

        $uids = Order::from('sp_order_2 as o')
            ->whereIn('o.sale_user_id', $sale_users)
            ->distinct('o.uid')
            ->pluck('o.uid');

        $list = Order::from('sp_order_2 as o')
            ->select(
                'o.id as order_id', 'o.trade_no', 'o.rent_total', 'o.status', 'o.reward', 'o.create_time'
                , 'u.faname', 'o.uid'
                , 'm.mobile'
                , 'm.cert_name'
                , 'og.goods_title'
            )
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->leftjoin('sp_sale_user as u', 'o.sale_user_id', 'u.sale_user_id')
            ->where($where)
            ->whereIn('o.uid', $uids)
            ->orderBy('o.id', 'desc')
            ->groupBy('o.id')
            ->paginate($pageSize);
        $list = obToArray($list);
        if (isset($list['data']) && $list['data']) {
            foreach ($list['data'] as $k => $item) {

                $sale_user_idu = Order::where('uid', $item['uid'])->orderBy('id', 'asc')->value('sale_user_id');
                if (!in_array($sale_user_idu, $sale_users)) {
                    $list['data'][$k]['trade_no'] = $item['trade_no'] . '已命中都来租的库';
                }

                //订单状态
                $list['data'][$k]['statusName'] = OrderService::ORDER_STATUS_NAME_LIST[$item['status']];
                //租期详情
                $orderLease = OrderLease::saleOrderLeaseDetail($item['order_id']);
                $list['data'][$k]['orderLease'] = $orderLease['orderLease'];
                if (!empty($orderLease['overdue_time'])) {
                    $list['data'][$k]['overdue_time'] = $orderLease['overdue_time'];
                }
                //总佣金
                $reward = $orderLease['reward_amount'] + $item['reward'];
                //已结算租金
                $paid_num_rent = $orderLease['paid_num_rent'] ? $orderLease['paid_num_rent'] : '0.00';
                if ($orderLease['reward'] == 1) { //结算固定金额
                    $paid_num = sprintf("%.2f", $paid_num_rent + $item['reward']);
                } else {
                    $paid_num = $paid_num_rent;
                }
                $list['data'][$k]['phone'] = substr_replace($item['mobile'], '***', 3, 3);
                $list['data'][$k]['cert_name'] = mb_substr($item['cert_name'], 0, 1, 'utf-8') . '*' . mb_substr($item['cert_name'], 2, 6, 'utf-8');
                $list['data'][$k]['reward'] = $paid_num . '/' . $reward;

                $list['data'][$k]['rent_total'] = $paid_num_rent . '/' . $item['rent_total'];

                $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            }
        }
        return $list;
    }

    /**
     * 征信订单列表
     * @param $request
     * @param array $where
     * @return array
     */
    public static function creditOrderList($request, $where = [])
    {
        $orderId = $request->input('orderId', '');  //订单ID
        $trade_no = $request->input('trade_no', ''); //订单号
        $cert_name = $request->input('cert_name', '');  //用户名
        $mobile = $request->input('mobile', ''); //手机号
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);

        if ($orderId) {
            $where[] = ['o.id', $orderId];
        }
        if ($trade_no) {
            $where[] = ['o.trade_no', 'like', '%' . $trade_no . '%'];
        }
        if ($cert_name) {
            $where[] = ['cb.cert_name', 'like', '%' . $cert_name . '%'];
        }
        if ($mobile) {
            $where[] = ['cb.mobile', 'like', '%' . $mobile . '%'];
        }
        $orderList = OrderCredit::from('sp_order_credit as cb')
            ->leftjoin('sp_order_2 as o', 'o.id', 'cb.order_id')
            ->leftjoin('sp_shop_user_2 as su', 'su.member_id', 'cb.member_id')
            ->select(
                'o.id', 'o.trade_no'
                , 'cb.cert_name', 'cb.mobile', 'cb.cert_no', 'cb.start_at', 'cb.end_at', 'cb.result2', 'cb.result3', 'cb.status_time', 'cb.member_id', 'cb.user_type', 'cb.result4', 'cb.status_time1', 'cb.result5', 'cb.status_time2', 'cb.result6', 'cb.status_time3'
                , 'su.shopname', 'su.mechanism'
            )
            ->where($where)
            ->groupBy('cb.order_id')
            ->orderBy('cb.start_at', 'desc');
        $list = obToArray($orderList->paginate(10));
        foreach ($list['data'] as $key => $value) {
            $list['data'][$key]['shopname'] = $value['user_type'] == OrderService::RISK_USER_TYPE_ADMIN ? '管理员' : $value['shopname'];
        }

        return $list;
    }


    //创建订单信息
    protected function createLineOrder($request, $user)
    {
        $amount = $request['amount'] ?? 1;
        $realname = $request['faname'];
        $mobile = $request['phone'];
        $address = $request['address'] ?? '线下门店自提';
        $goods_id = $request['phoneGoods'];
        $setmeal_id = $request['phoneSetmeal'];
        $spec_id = $request['spec_id'];
        $is_renewal = isset($request['is_renewal']) ? $request['is_renewal'] : self::ORDER_NOT_RENEWAL;
        $relation_id = isset($request['relationId']) ? $request['relationId'] : '';
        $pact_type = isset($request['pact_type']) ? $request['pact_type'] : '2';
        $emergency_contact = isset($request['emergency_contact']) ? $request['emergency_contact'] : '';
        $contact_name = isset($request['contact_name']) ? $request['contact_name'] : '';
        $contact_mobile = isset($request['contact_mobile']) ? $request['contact_mobile'] : '';
        $insurance = isset($request['insurance']) ? $request['insurance'] : '7';
        //推广参数
        $shopname = isset($request['shopname']) ? $request['shopname'] : '';
        $seller_id = ShopUser::where('shopname', $shopname)->value('member_id');
        if (empty($seller_id)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请扫商家二维码', 'data' => []];
        } else {
            $address = $shopname . $address;
        }
        $resOrder = Order::where('uid', $user['id'])->whereIn('status', [OrderService::ORDER_STATUS_NOT_PAY, OrderService::ORDER_STATUS_SIGN_NOTPAY, OrderService::ORDER_STATUS_SIGN_NOCHECK])->value('id');
        if ($resOrder) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '存在待审核订单，请勿重复提交订单', 'data' => []];
        }

        if (empty($amount)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请选择商品数量', 'data' => []];
        }

        if (empty($realname) || empty($mobile) || empty($address)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '收货人手机号或姓名地址不能为空', 'data' => []];
        }
        if (empty($goods_id) || empty($setmeal_id) || empty($spec_id)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '缺少商品参数', 'data' => []];
        }
        //非续租减库存
        if ($is_renewal == Order::ORDER_NOT_RENEWAL) {
            GoodsSetmeal::where([['goods_id', $goods_id], ['id', $setmeal_id]])->decrement('quantity', $amount);
        }

        $config = Config::settingDetail();
        $age = getAgeByID($user['cert_no']);
        if ($user['cert_no']) {
            if ($age < $config['min_age'] || $age > $config['max_age']) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '您年龄不符合要求', 'data' => []];//，需要大于18岁小于40岁
            }
        }

        //商品
        $goods = Goods::checkGoodsStatus($goods_id);
        if (empty($goods)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '商品不存在', 'data' => []];
        }

        if (empty($contact_name) || empty($contact_mobile)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '该订单必须填写紧急联系人信息，如页面无输入框，请下拉刷新页面！', 'data' => []];
        }
        if (trim($realname) == trim($contact_name) || trim($mobile) == trim($contact_mobile)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人信息不能与收货人信息一致', 'data' => []];
        }
        //套餐
        $setmeal = GoodsSetmeal::CheckGoodsSetmeal($goods_id, $setmeal_id);
        if (empty($setmeal)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '套餐不存在', 'data' => []];
        }
        //租期
        $spec = GoodsSpec::CheckGoodsSpec($goods_id, $setmeal_id, $spec_id);
        if (empty($spec)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '租期信息不存在', 'data' => []];
        }


        $order_data = [];
        $order_sn = createNo();
        if ($seller_id) {
            $order_data['seller_id'] = $seller_id;
        }
        $insurance_money = '0.00';
        if ($insurance) {
            $order_data['is_insurance_choose'] = $insurance;
            $insurance_money = GoodsService::getGoodsInsurance($insurance);
        }

        //生成账单
        $agreetype = $request['isAgree'];
        $salePrice = $request['salePrice'];
        $salePricea = $request['salePricea'];
        $firstRent = bcmul($salePricea * $agreetype, 0.1, 2) + 100;

        if ($agreetype == '4') {
            $idindex = 9;
            $eRent = bcdiv($salePrice - $firstRent, 8, 2);
        } else {
            $idindex = 6;
            $eRent = bcdiv($salePrice - $firstRent, 5, 2);
        }

        $order_data['uid'] = $user['id'];
        $order_data['trade_no'] = $order_sn;
        $order_data['remark'] = '花呗总额度:' . $request['huabeiAmount'] . '；' . '芝麻信用分:' . $request['zhimaScore'];
        $order_data['user_email'] = !empty($request['email']) ? $request['email'] : '';
        $order_data['realname'] = $realname;
        $order_data['mobile'] = $mobile;
        $order_data['address'] = preg_replace('/\s*/', '', stripslashes(strval($address)));
        $order_data['prov'] = !empty($request['prov']) ? $request['prov'] : '';
        $order_data['city'] = !empty($request['city']) ? $request['city'] : '';
        $order_data['area'] = !empty($request['area']) ? $request['area'] : '';
        $order_data['create_time'] = time();
        $order_data['update_time'] = time();
        $order_data['amount'] = intval($amount);
        $order_data['pay_type'] = $goods['pay_type'];
        $order_data['payer_user_id'] = $user['user_id'];

//定位位置 手机品牌

        $location = isset($request['location']) ? $request['location'] : '';
        $location = isset($location['province']) ? $location['province'] . $location['city'] . $location['district'] . $location['streetNumber']['street'] . $location['streetNumber']['number'] : $location;
        $order_data['location'] = $location;
        $order_data['phone_brand'] = isset($request['phone_brand']) ? $request['phone_brand'] : '';


        if (!empty($contact_name) && !empty($contact_mobile)) {
            $order_data['emergency_contact'] = $contact_name . $contact_mobile;
        }
        $order_from = !empty($request['order_from']) ? $request['order_from'] : 'search';
        $order_data['order_from'] = $order_from;

        $order_data['relation_id'] = $relation_id;
        $order_data['contract_type'] = $goods['contract_type'];
        $order_data['sign_num'] = $goods['sign_num'];
        $order_data['is_insurance'] = $goods['is_insurance'];
        $shopuser = ShopUser::where('member_id', $goods['member_id'])->select('account', 'account_type')->first();
        $shopuser = obToArray($shopuser);
        $shopRecharge = ShopRecharge::where('member_id', $goods['member_id'])->select('risk_credit_status', 'risk_credit_amount')->first();
        $shopRecharge = obToArray($shopRecharge);
        $order_data['is_skip'] = self::RISK_SKIP_YES;
        if (!empty($shopRecharge)) {
            $order_data['is_skip'] = $shopRecharge['risk_credit_status'] == ShopRecharge::SERVICE_STATUS_OPEN ? self::RISK_SKIP_NOT : self::RISK_SKIP_YES;
        }
        if (!empty($shopuser)) {
            $order_data['financing_type'] = $shopuser['account'];
        }
        $begin_time = date("Y-m-d H:i:s", time());//租期开始时间
        $order_data['begin_time'] = $begin_time;
        if (date("d", $begin_time) >= 28) {
            $order_data['end_time'] = strtotime('last day of + ' . $idindex . ' month', time());
        } else {
            $order_data['end_time'] = date("Y-m-d H:i:s", strtotime('+ ' . $idindex . ' month', time()));;
        }

        $order_data['form_id'] = isset($request['form_id']) ? $request['form_id'] : '';//模板消息form_id

        if (empty($order_data['seller_id'])) {
            $order_data['seller_id'] = '1731928096';
        }
        $order_data['status'] = isset($request['status']) ? $request['status'] : OrderService::ORDER_STATUS_NOT_PAY; //待认证

        $order_data['month_total'] = $idindex;
        $order_data['rent_total'] = $salePrice;
        $order_data['foregift'] = $salePrice;

        DB::beginTransaction();
        $order_id = $this->insertGetId($order_data);

        if ($order_id) {
            //费率查询记录
            $month_num = getMonthNum($begin_time, $order_data['end_time']);
            OrderRate::addOrderRate($order_id, $goods_id, $order_from, $goods['member_id'], self::RISK_SKIP_YES, $month_num, $shopuser['account'], '', '', $goods['pay_type']);


            $dataLease = [];
            for ($i = 0; $i < $idindex; $i++) {
                $which_period = $i + 1;
                if ($which_period == 1) {
                    $ra['begin_time'] = time();
                    $begin_time = $ra['begin_time'];
                } else {
                    if (date("d", $begin_time) >= 28) {
                        $ra['begin_time'] = strtotime('last day of + 1 month', $begin_time);
                        $begin_time = strtotime('last day of + 1 month', $begin_time);
                    } else {
                        $ra['begin_time'] = strtotime('+ 1 month', $begin_time);
                        $begin_time = strtotime('+ 1 month', $begin_time);
                    }
                }

                $dataLease[$i]['order_id'] = $order_id;
                $dataLease[$i]['which_period'] = $which_period;
                $dataLease[$i]['begin_time'] = $begin_time;
                $dataLease[$i]['end_time'] = strtotime('+ 1 month', $begin_time);;
                if ($i == 0) {
                    $dataLease[$i]['rent'] = $firstRent;
                } else {
                    $dataLease[$i]['rent'] = $eRent;
                }
                $dataLease[$i]['create_time'] = time();
                $dataLease[$i]['paid_rent'] = 0;
                $dataLease[$i]['pay_type'] = 1;
            }

            $res_data = OrderLease::insert($dataLease);

            $order_goods_data = [];
            $order_goods_data['order_id'] = $order_id;
            $order_goods_data['goods_id'] = intval($goods_id);
            $order_goods_data['goods_title'] = $goods['title'];
            $order_goods_data['pact_type'] = $pact_type;
            $order_goods_data['imgurl'] = $goods['imgurl'];
            $order_goods_data['convey_type1'] = $goods['convey_type1'];
            $order_goods_data['convey_type2'] = $goods['convey_type2'];
            $order_goods_data['setmeal_id'] = intval($setmeal_id);
            $order_goods_data['setmeal_title'] = $setmeal['title'];
            $order_goods_data['lease_set'] = $setmeal['lease_set'];
            $order_goods_data['spec_id'] = $spec_id;
            $order_goods_data['lease_time'] = $spec['lease_time'];
            $order_goods_data['lease_price'] = $spec['lease_price'];
            $order_goods_data['setmeal_price'] = $setmeal['buyout_price'];
            $order_goods_data['website_price'] = $setmeal['price'];
            if ($is_renewal == self::ORDER_IS_RENEWAL) {
                $order_goods_data['start_date'] = $setmeal['start_date'];
            } else {
                $order_goods_data['start_date'] = 0;
            }
            if ($pact_type == GoodsService::GOODS_PACT_TYPE_GIVE) {
                $order_goods_data['setmeal_foregift'] = $order_data['rent_total'] + $insurance_money;
                $order_goods_data['setmeal_price'] = 0;
            } else {
                $order_goods_data['setmeal_price'] = $setmeal['buyout_price'] > 0 ? $setmeal['buyout_price'] : 0;
                $order_goods_data['setmeal_foregift'] = $order_data['rent_total'] + $order_goods_data['setmeal_price'] + $insurance_money;
            }
            $order_goods_data['is_buy_out'] = $setmeal['is_buy_out'];
            $order_goods_data['create_time'] = time();
            $res = OrderGoods::insert($order_goods_data);


            if ($res) {
                DB::commit();
                $data['order_id'] = $order_id;
                AlipayMessageService::sendChangeOrderMessage($order_id);

                return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '订单创建成功', 'data' => $data];
            } else {
                DB::rollBack();
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单创建失败', 'data' => []];
            }
        } else {
            DB::rollBack();
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单创建失败', 'data' => []];
        }
    }

    /**
     * 订单列表
     * @param $request
     * @param array $where
     * @return array
     */
    public static function orderXxfList($request, $where = [])
    {
        $riskName = $request->input('username', '');
        $riskMobile = $request->input('riskMobile', '');
        $orderCreateTime = $request->input('orderCreateTime', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $begin_time=strtotime(date('2025-03-15'));
        $end_time=strtotime('-3 days');
        $where[] = ['o.create_time','>', $begin_time];
        $where[] = ['o.create_time','<', $end_time];
        $where[] = ['o.status',OrderService::ORDER_STATUS_CENCEL];
        $radar = $request->input('radar', 0);
        $order_ids = $request->input('order_ids', '');
        $user_status= $request->input('user_status', '');
        $phone_brand= $request->input('phone_brand', '');

        if ($phone_brand) {
            $where[] = ['o.phone_brand', 'like', '%' . $phone_brand . '%'];
        }
        if ($riskName) {
            $where[] = ['m.cert_name', 'like', '%' . $riskName . '%'];
        }

        if ($riskMobile) {
            $where[] = ['m.mobile', $riskMobile];
        }

        if ($orderCreateTime) {
            $orderCreateTime = explode('~', $orderCreateTime);
            $where[] = ['o.create_time', '>=', strtotime($orderCreateTime[0])<$begin_time?$begin_time:strtotime($orderCreateTime[0])];
            $where[] = ['o.create_time', '<=', strtotime($orderCreateTime[1])>$end_time?$end_time:strtotime($orderCreateTime[1])];
        }

        $uid=Order::query()->where('status','>',4)->pluck('uid');
        $uid=obToArray($uid);
        $users = MemberOther::query()->whereBetween(DB::raw('YEAR(CURDATE()) - SUBSTR(cert_no, 7, 4)'), [20, 41])->pluck('id');
        $users=obToArray($users);
        if ($radar) {

            if($radar==2){
                $orderList = Order::query()->from('sp_order_2 as o')
                    ->where('m.cert_name', '<>','0')
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->leftJoin('sp_order_radar_xinyan as or', 'or.order_id', 'o.id')
                    ->groupBy('m.cert_no')
                    ->whereNotIn('o.uid', $uid)
                    ->whereIn('o.uid', $users)
                    ->where('or.order_id', '<>', '')
                    ->where('or.member_id', '1693377836')
                    ->select(
                        'o.id','o.create_time',  'o.username','o.status','o.phone_brand', 'm.mobile', 'm.cert_name', 'm.cert_no',
                    )
                    ->where($where);
                if($order_ids||$user_status){
                    $orderList->whereIn('o.id', $order_ids);
                }

                $orderList->orderBy('o.update_time', 'desc');
                $list = obToArray($orderList->paginate($pageSize));
            }else{
                $orderids=OrderRadarXinyan::query()
                    ->where('order_id', '<>', '')
                    ->where('member_id', '1693377836')
                    ->pluck('order_id');
                $orderList = Order::query()->from('sp_order_2 as o')
                    ->where('m.cert_name', '<>','0')
                    ->whereNotIn('o.uid', $uid)
                    ->whereIn('o.uid', $users)
                    ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                    ->groupBy('m.cert_no')
                    ->whereNotIn('o.id',  $orderids)
                    ->select(
                        'o.id','o.create_time',  'o.username','o.status','o.phone_brand', 'm.mobile', 'm.cert_name', 'm.cert_no',
                    )
                    ->where($where);
                if($order_ids||$user_status){
                    $orderList->whereIn('o.id', $order_ids);
                }
                $orderList->orderBy('o.update_time', 'desc');
                $list = obToArray($orderList->paginate($pageSize));
            }

        }else {

            $orderList = Order::query()->from('sp_order_2 as o')
                ->where('m.cert_name', '<>', '0')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->whereNotIn('o.uid', $uid)
                ->whereIn('o.uid', $users)
                ->groupBy('m.cert_no')
                ->select(
                    'o.id', 'o.create_time', 'o.username', 'o.status', 'o.phone_brand', 'm.mobile', 'm.cert_name', 'm.cert_no',
                )
                ->where($where);
            if($order_ids||$user_status){
                $orderList->whereIn('o.id', $order_ids);
            }
            $orderList->orderBy('o.update_time', 'desc');
            $list = obToArray($orderList->paginate($pageSize));
        }

        if (isset($list['data'])) {
            foreach ($list['data'] as $k => $value) {

                $list['data'][$k]['radar']=OrderRadarXinyan::query()->where('order_id',$value['id'])
                    ->where('member_id', '1693377836')
                    ->exists();
                $age=getAgeByID($value['cert_no']);

                $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
                $authenticLog = AuthenticLog::where(['order_id' => $value['id'], 'status' => AuthenticLog::AUTHENTIC_STATUS_PASS])->select('status')->first();
                $list['data'][$k]['authentic'] = [
                    'age' => $age,
                    'sex' => get_sex($value['cert_no']),
                    'status' => $authenticLog ? AuthenticLog::AUTHENTIC_STATUS_PASS : AuthenticLog::AUTHENTIC_STATUS_REFUSE,
                ];
                if(!$list['data'][$k]['radar']){
                    $list['data'][$k]['cert_name'] =mb_substr($value['cert_name'], 0, 1, 'utf-8') . '*' ;
                    $list['data'][$k]['cert_no'] = '******';
                    $list['data'][$k]['mobile'] = '******';
                }
                $risk_level=OrderDlzwRisk::query()->where('order_id',$value['id'])
                    ->value('risk_level');
                $list['data'][$k]['cert_name']=$list['data'][$k]['cert_name'].' '.$risk_level;


            }
        }


        return ['list'=>$list];
    }


}
